\chapter{Introduction}
The goal of my thesis is to create a~piece of software which will be used as a~framework for dealing with a~robot development, programming and usage of robots.
The definition at this point is very wide and narrow at once and I~think it needs a~bit of a~clarification. By the~word robot I~do not only refer to an~autonomous
device or any other of these restrictive meanings.
Wikipedia defines robot as a~mechanical device that can perform tasks automatically. It may –
but need not – be humanoid in appearance. Some robots require some degree of guidance, 
which may be done by using a~remote control, or with a~computer
interface~\cite{wiki:robot}. So the~robot for our purpose is basically any
external devices that does something. Through the~project I~will often refer to
the term Device. It can represent either real world device or even any
simulation.

The point of the~thesis is not to create only some application and deliver it as
a finished bundle.
This project aims to be so much more than that. It will be an~universal platform
publishing an~API to other developers so they can continue with their extensions
where this project ends. Example might be creating a~simulation environment for
students to practice algorithms for path finding and learning in the~Artificial Intelligence. Or to
create a~platform for guidance of external devices - robots - with their
artificial intelligence brain located on the~PC rather than in the~device itself because implementation of complex AI directly into the
target device could be challenging.
Some of these implementations will be a~part
of the~project to demonstrate how is the~extension system designed and to
prepare some basic implementations to make it a~little easier for others.

Why would we stop here? This project might go further to become a~kind of robot
development IDE. This would require to have a~community around the~application
to provide certain stream of new features and enhancement. It is hard to
estimate if this will or will not happen. But this goal - easy extendability -
will be taken into consideration during the~analysis and technologies selection.

The vital requirement of this application is to be portable. More and
more users are switching to the~free software and alternatives to the~mainstream
systems. Mostly to some distributions of the~Linux\footnote{To be fair it
shouldn't just be called Linux but rather GNU/Linux as it is a~combination of
kernel together with many GNU tools. Free GNU operating system was in the~development
even before Linus Torvalds stared to write his kernel~\cite{gnu:gnuLinuxFAQ}.}.
What is important is that majority of these users are connected to computer
science in some way. I~personally am a~member of this group and I~like to have
my software available for both Microsoft Windows and Linux computers.

This project is build on the~top of the~knowledge and experience gathered during
creation of my Bachelor Thesis. Although the~topic is completely different from
the one in the~Bachelor Thesis, technology and part of the~frameworks is the
same. Therefore some Chapters are based on the~information published in by
Bachelor Thesis. Same principal applies to the~code base. The~application itself
is totally different but it is still the~Eclipse based product. So this project
can be considered a~kind of follow up of my Bachelor Thesis.

This piece of software will be released under the~terms of the~LGPL license
version 3 from 2007 written by Richard Stallman from the~Free Software
Foundation. This license specifies terms under which this software can be
distributed, changed, copied and used. I~have selected LGPL to ensure that this
application can be developed and maintained by the~community after its release.
This is an~important point to the~idea of future extensions and maintenance as
described before. Following fact about the~LGPL license supports the~previous
requirements even more.
Under the~terms of LGPL one can modify the~software if he feels the~need and if
he decides to publish version with the~modification he must make a~source code
available. This way developers are able to build up on his improvements.

\chapter{Goals Description, Objectives}
\label{chap:goalDesc,Obj}

\section{Structure of the~Thesis}
This thesis is structured in the~similar manner as any software development.
First, goals, objectives and ground features have to be established. This is
done further in this Chapter~\ref{chap:goalDesc,Obj}. Before the~analysis can be
done I~have to choose the~technologies first and I~will do this in
Chapters~\ref{chap:choosingProgrammingLanguage} and~\ref{chap:frameworks}.
Analysis will refer to specific technologies and parts of frameworks. Doing the~analysis before the~technologies
would be pointless. One more thing has to be taken care of before
getting to that analysis. While suitable and fully featured IDE containing
advanced refactoring, code completion, potential error discovery and many
other features can save more than 50\% of the~developer's time, I~really want to
spend some time selecting it. So the~selection of the~IDE will be described in
Chapter~\ref{chap:IDE}.

Now the~analysis can take place. There are many forms of analysis in the~world
of software development. They range from very informal descriptions of basic
capabilities together with few hand-drawn screens to the~very formal thousand
pages long books which describe every detail of a~final product and sometimes
can be more or less used to generate parts of the~system automatically. I~actually find both of these approaches extreme and useless in practice. The~middle way has to be found. Anyway you will find the~analysis in
Chapter~\ref{chap:aandd}.

After the~analysis I~will dive into details of the~implementation. I~will omit
boring and obvious parts and will focus on hitches, important decisions and
information which might be useful for anybody else going the~same technology
direction. This will take place in Chapter~\ref{chap:implementationOfTheCore}. I~will describe two extensions of the~core in the~form of the~Dummy Device which
basically is the~simulation of the~moving robot on the~map.
Its description can be found in Chapter~\ref{chap:dummyDevice}.

The vital part of any software product should be testing. Some parts will be
tested by usability tests, some by automated tests and you can read about it in
Chapter~\ref{chap:testing}.

Last but not least is the~conclusion and it can be found in Chapter
\ref{chap:conclusion}.
At the~end I~will evaluate my work, identify what was done and were I~encountered problems. I~will also go into some
possibilities of future extensions of the~project and its perspectives.

\section{Goals}

As I~mentioned in the~introduction, my goal is not only to create final
application, but to deliver open source platform on which one can start building
his own solution that would suit his needs. In
Chapters~\ref{chap:choosingProgrammingLanguage},~\ref{chap:frameworks}
and~\ref{chap:aandd} I~will explain decisions which will be accepted to assure
possibility of established goals.

The application will be user friendly and following common principals in the
graphic users interface design to minimize steepness of the~learning
curve in the~area of common use cases\footnote{Learning curve is a~graphical
representation of the~changing rate of learning~\cite{wiki:learningCurve}. In
this case it is used as general expression for necessary amount of effort to learn how to use this application.}
Using of existing standard library of components will be considered as it is the
easiest way of how to provide this kind of comfort and quick access to all
important functions and available actions. Application should also incorporate
some form of help to cover areas which are not clear form the~common rules.

While this application is intended to some extent to communicate with some
external HW I~decided to narrow the~objective to the~rich client
application. Term rich client application comes from the~rich user
experience. There was a~huge progress in web applications in the~past few years
and the~experience of using some of them can also be easily called rich. For our
purpose we will consider rich client application to be thick client i.e.
application independent of the~central server. Although thick client has to be
installed on the~client's computer which can cause some difficulties, it can
provide look and feel that is common to most of applications running on that
machine and it can ensure much better access to native system resources than
thin client.

\section{API Objective}
\label{sec:APIObjectives}
There is the~objective that raises above all others. As
repeated for several times this piece of software should be extended in the~future and while lifecycle of
application usually exceeds its designed lifespan it must provide well
thought-out API. The~issue with APIs is that it cannot be modified in
the~future.
Any change in the~API can break existing code. The~only way one can modify API
is to provide new methods\footnote{Method in this context stands for general
point of access rather than some specific element of any programming language.}.
This can be useful for extension of the~API but not for fixing problems from the
past. This is the~reason why you can find a~lot of interfaces with number two in
the name. Designers decided that it is less pain to provide both old unchanged
API together with new one.

Previous paragraph describes the~problem. My solution of this problem is to use
some framework that covers substantial part of the~API. My goal is not to
reinvent the~wheel. I~will rather concentrate on enriching of the~existing
framework by new features that can be to some use to the~client or future
developer. Using some framework that allows easy future extensions then can be
considered a~non-functional requirement. More about framework selection can be
found in Chapter~\ref{chap:frameworks}.

\section{Motivation}
There are actually two strong motivations that drove me to this project. First
is my passion for moving hardware. Same as any man I~like everything that moves
and makes sounds. For past few years I~have been playing around with microcomputer
development for basic devices. I~used different toolchains during the~time but
most of these toolchains ends with uploading your program to the~microcomputer.
What I~missed was some platform in which I~can implement logic or
AI\footnote{It is a~bold statement that I~really implemented some serious AI
but let's say that even some complex logic is AI for now.}. It was hard
to debug any communication between a~device and a~computer and not just that.
During years, the~idea of framework that can run programs in some scripting
language, provides instant support for adding new devices or features to
existing devices shaped in my head. More about specific features of this project
will be mentioned in the~section~\ref{sec:requiredFeatures}.  

Second one - I~really love extendable open projects which anybody can
contribute into or modify it to be able to use it for his exact needs rather
than staying with closed software which lacks some necessary features. After some 
research I~found out that there is a~plenty of applications or IDEs available 
for specific hardware. These could be really good to use if you actually have 
that HW or you want to simulate usage of that particular HW. However when the
time comes and you create your own small robot, these existing platforms are not
much of a~use. This might be the~reason why the~most of the~creators of these
devices either do not incorporate PC communication into the~project or they create specific application for each
device. The~second one may be fine but spending time creating everything from
basic routines to the~UI from the~scratch every time or reusing and reshaping
existing solutions can be a~bit of the~pain.

\section{Required Features}
\label{sec:requiredFeatures}
Required features usually come from the~process of requirements gathering and
analysis.
The only real goal of this process is to find out what the~stakeholder really
wants and needs. Once we have this information we have to describe them formally
to be able to define project boundaries. In this case, while I~am both the
stakeholder and the~designer of the~application, it was more of the~inner talk.
The description of requirements gathering is for this reason intentionally
omitted and I~will describe only results. This list of required features only
covers needs for the~core of the~application. This core fulfil the~need for
some configuration and execution environment for the~devices. Common features
such as saving of the~data, opening files, resizing a~window and many others
are left out as obvious.

\subsection{General Description of the~Structure}
\label{subsec:descriptionOfStructure}
The basic structure of the~application is something called Session. This is a~container that connects all other objects of the~problem domain together,
describes them and is possible to be executed.

\begin{samepage}
Session can contain following four classes of objects.
\begin{itemize}
  \item Device,
  \item Module,
  \item Monitor,
  \item Program.
\end{itemize}
\end{samepage}

These four classes are abstract representation of real life entities and
encapsulate actions and properties that each class provides and requires.
There is also one important object called Environment which goes through all
objects. Each class will be now described into more details.

\subsection{Device}
Device represents real hardware device or some simulation of an~abstract or a~real device.
Implementation of this class is responsible for encapsulation of the
communication with the~device. It should monitor its state and pass requests for information to the~devices as well as
commands. One physical or simulated device should be represented by one instance
of the~Device class. There might be some exceptions if the~real device consists
from more separated components.

The purpose of this class is to hide implementation details of each device and
to publish only relevant API for the~rest of the~application rather than
allowing direct access to the~device from other parts of the~code.

Tha device can be configurable. The~configuration varies between
implementations.
It can be used for communication specification, for initial values or any other
necessary information.

\subsection{Module}
\label{subsec:module}
Purpose of Module is to propagate some functionality of the~Device. It can be
well described by the~analogy with the~way how hardware is used in the~PC.
Module represents a~HW driver which publishes some functionality and API with
client's application not caring about the~implementation details. Device can be
compared to the~firmware in this analogy.

Each implementation of the~Module should publish the~type of the~Device it
requires if some. Module should publish its API which can be used from the~other
parts of the~application. It encapsulates any communication between a~Program
and a~Device.

It should be possible to create macro Modules. Macro Module is a~Module that
provides functionality based on more sub Modules. It uses their published APIs
and translate requests to the~sub Modules with some added functionality.

Module can be configurable. Configuration can be again used for anything and
will vary between implementations.

\subsection{Program}
Program is an~abstraction of any Program that can use existing stack of Modules
and Devices. It can be implemented in any language using any syntax and can be
evaluated either internally or externally. It is up to the~implementation if it
will allow user to use any Module or just some designated set of Modules which
are supported by the~Program.

More than one Program can be assigned to the~same chain. Each Programs should
run independently. It is responsibility of Modules to take care of
synchronization and atomic operations if necessary.

Program can be configured. Each implementation is free to have any
configuration. It is mostly intended for easy modification of environmental
constants of the~Program rather than changing them directly in the~Program to be
able to debug algorithms easily.

\subsection{Monitor}
Monitor stands little bit aside from the~chain described up to this point. Till
now everything was clear. Device is at the~bottom, Module encapsulates its
functionality and Program uses Modules to do whatever. Call structure is pretty
straight forward. Program requests or commands Module to do something, Module
either does it or pass it to the~Device. When the~command is passed to the
Device or response is gathered for the~request, information then flows back to
the Program.

The purpose of the~Monitors is to observe Modules and
changes in their state.
It is responsibility of the~Module to notify all registered listeners if some
events specific for each Module occur. This is a~beautiful point for observer
pattern implementation.

Monitor will have two possible ways of use. It can be used for output of the
information in any form. It can be output to the~log window, to the~file or even
visualisation of some components. It is up to target application to use Monitors
for this.

Other possibility is to enforce rules into the~execution of the~Session. If
there are situations when the~rules are broken and execution should be stopped
for any reason, Monitor can do that by using API published by Environment
described below.
Rules can represent anything from going out of the~map in the~simulation to the
overheating of motors in real robots.


\subsection{Session}
Now after describing the~stack of available classes it might be clear why one
need a~Session - a~container - to prepare combination of implementations of
those classes. The~Session should have a~name. It should have a~list of
implementation of each class of elements. It should have system for validation
based on requirements of different classes for implementations of other classes.

\subsubsection{Session Preparation and Configuration}
During the~Session preparation user will add implementation of each (or subset)
of classes. Most of the~classes can have some kind of configuration. Each
implementation should publish which configuration is needed and tools for
preparation and application of this configuration.

Once these implementations - let's call them system objects - are on their
places, one will validate the~Session. The~Session cannot be  executed until it
is validated successfully. The~validation should check consistency of the
system objects combination. If some classes publish kind of prerequisites
these should be checked. If it is possible Programs should be checked for syntax
up to the~possible extent.

\subsubsection{Session Execution}
Once validated Session can be executed. Execution of the~Session consist of
instantiation all necessary system objects, exchange of necessary pointers and
information between them and then of starting each Program. Execution ends when
all Programs finished or stop signal was thrown. As described in the~Program
section there can be more than one Program running. Each Program must run
independently preferably in its own thread or process.

Before execution, Environment object is created and its instance is shared
between all system objects in one execution.

\subsection{Environment}
Environment object is a~tool of communication between system objects without the
need to know about each other. It provides tools for throwing stop signal which
is then delivered to all listening components of the~execution. It provides
facility for Modules to dispatch events to all listeners without direct
interaction with them.

It should also provide a~common logging facility. While components or system
objects are basically independent of each other, the~Environment is the~only
point that is common to all of them. If user wants to have common logging point he
should use logging facility available in the~Environment.

API of the~Environment object is expected to expand during the~time while there
might be some new needs for common communication. Anyway it is recommended that
Environment stays independent of the~implementation of these facilities and
rather uses delegation to some other facilities to provide the~functionality to
be able to easily change the~implementation of the~features without touching the
API because of reasons described in~\ref{sec:APIObjectives}.

\chapter{Current Solutions}
\label{chap:currentSolutions}
Before the~discussion about the~current solution can take place, I~should bring
back the~goals of this project. Main goal of this project is to prepare
platform. Open, extendable, well designed and robust platform. Purpose of this
platform is to bring available IDE for minor projects and to hobbyists or
anybody else who wants to be able to tweak or bend the~capabilities of the
framework to the~form which is most suitable for his needs. The~goal is not to
create complete IDE or simulation framework for robotics. This would be far
beyond the~reach of the~boundaries of this project. Creation of the~solution
specific to one technology or vendor is also not the~goal.

With the~content of the~previous paragraph in mind, we can see that there
basically is no direct concurrent piece of software or I~was not able to find it. There are projects similar to
this one though. To be able to compare several products, I~will take into
consideration even pieces that don't match all the~criteria. Rest of the~open
projects for robotics simulation are mostly aimed to the~certain vendor or only to the~3D visualization of the~environment. 

\section{The Player Project}
The Player Project (formerly the~Player/Stage Project) is a~project to create
free software for research into robotics and sensor
systems~\cite{wiki:playerProject}. It is divided into three subprojects -
Player, Stage and Gazebo. It is the~closest one to our project.
\subsection{Player}
Player component can be described as a~robot abstraction layer~\cite{wiki:playerProject}. This layer let's developer to concentrate on creation
of the~robot's AI or any other desired functionality rather than on the
implementation of the~communication, interpretation of the~raw sensor data or
some other job that has already been achieved by somebody else.

The abstraction is good enough to allow use simulation backend instead of the
real hardware with minor or no changes to the~code.

This part is very similar to the~concept of Modules in my project as described
in section~\ref{subsec:module}.

\subsection{Stage}
The Stage is a~2D simulator of the~environment. It is capable of simulation of
multiple robots in one Session. It can be used together with the~Player to
replace the~real hardware and to provide virtual input to the~robot's sensors.

\subsection{Gazebo}
Gazebo is the~3D simulation environment. It integrates the~Open Dynamics
Engine\footnote{\url{http://en.wikipedia.org/wiki/Open_Dynamics_Engine}}
together with OpenGL. It also supports provisioning of the~input data to the
sensors of the~Player part. It has actually been moved from the~Player project
to the~separate Gazebo project in 2011.

\section{Webots}
Webots is a~development environment used to model, program and simulate mobile
robots~\cite{webots}. This sounds very promising. Features of the~project
include 3D animations, multiple robots in one environment, object collision
detection, dynamics and much more.

Free limited version is offered or professional edition can be bought.
Unfortunately it is not an~open source project. It provides extensive APIs.

\section{Microsoft Robotics Developer Studio}
Official website of this product provides following description. Microsoft
Robotics Developer Studio 4 (RDS 4) provides a~wide range of support to help make it easy to develop robot applications. RDS 4 includes a~programming 
model that helps make it easy to develop asynchronous, state-driven
applications~\cite{MSRobotics}.

I found it to be a~nice complete package for robotics simulation and
realization. It can be downloaded for free. It is not an~open source project. I~didn't find any information about possibilities to extend current functionality
of this product.

\section{Conclusion}
Player project is actively developed\footnote{At the~time of writing of this
thesis based on the~public svn at \url{http://playerstage.svn.sourceforge.net/}}
and is in its substance similar to my project. But its direction is not the
same. It is focused directly on robotics together with advanced sensors. It is
known to be complex to install and use. Most important thing from my point of
view is that it is too focused to the~science and professional robotics and
this is not the~aim of my project as I~stated at the~beginning of this Chapter and in the
general description. Both of other products are not licenced under an~open
source licence. Table~\ref{tab:competition} summarizes fulfilment of requirements by each
competitor against this product.

\begin{table}[h]
\centering
\caption{Fulfilment of Project Requirements By Competition}
\begin{tabular}{|l|c|c|c|c|c|}
\hline
Product Name & Simulation & HW Driving & Extensible & Open Source
\\ 
\hline
Player Project & Yes & Yes & No & Yes\\
\hline
Webots & Yes & Yes & Yes & No \\
\hline
Microsoft RDS & Yes & Yes & Yes & No \\
\hline
This Project & Yes & Yes & Yes & Yes\\
\hline
\end{tabular}
\label{tab:competition}
\end{table}

As mentioned at the~beginning of this Chapter this project is very specific in
what it is. It is an~open platform for abstraction of any device or simulation
and for interconnection of these device together with capability of programming
or scripting of the~behavior of these devices. I~haven't found any project that
has the~same goal and actually it was the~point where I~decided to start this
project.

\chapter{Choosing Programming Language}
\label{chap:choosingProgrammingLanguage}
In Chapter~\ref{chap:goalDesc,Obj} I~have defined basic guidelines of the
project together with structure of the~core part. Now I~will describe the~way
of finding the~most suitable technologies to achieve this goal. Technologies
should support all the~necessary features for the~project but it should also
encourage community to contribute into it. Selecting technology which might be
slightly more powerful but is not generally popular or even unknown wouldn't
help in the~future. The~resulting technology should be a~good trade off between
popularity and compliance with the~given task.

Programming language is our first and most important stop. Most of the
frameworks, UI libraries and IDEs are designed to work only with one language.
This selection then narrows the~upcoming parts of the~process. 

\section{C++}
Probably everybody is at least a~little bit familiar with the~C++ programming
language. It has been around since 1985 developed by Bjarne Stroustrup and it
has spread from miniature devices to mainstream operating systems. To be more
formal, C++ is a~statically typed, free-form, multi-paradigm, compiled, general-purpose programming
language~\cite{wiki:cpp}. 

While C++ is compiled language it can easily access low-level system functions,
resources and hardware. This might be advantage in one part of the~project and
disadvantage in all others. From my point of view C++ supports some very
powerful facilities that can become a~great danger to the~project. I~am talking
about pointer arithmetics, multiple inheritance, assembler inlining, and more.
On the~other hand it lacks built-in multithreading support\footnote{Although there
is multithreading support library.}, doesn't come with security and has manual
memory management. Manual memory management can definitely be more efficient
while we can precisely define the~life-cycle of objects and there is no need for
additional work searching for objects that can be destroyed. This claim only
stands if the~coder is 100\% accurate and does not make any mistakes. And I~know
I make them. One more thing to consider is future of the~projects. Even if I~will not use the~multiple inheritance even if it is available because I~see a~danger behind that future contributor might find it marvellous but might not
know how to use it properly.

\section{.NET}
The .NET is a~framework developed by Microsoft and is widely spread through the
Microsoft world. It has a~cool thing called language interoperability. You can
compile code from different languages into some form of byte code and because
.NET runs programs in the~virtual machine rather than directly on hardware it
can interpret multiple languages~\cite{wiki:dotnot}.

I am mentioning this technology because I~think that there is some potential to
C\# and whole framework. Problem is that .NET framework is not really portable
to other platforms and one of the~basic specifications of the~project is just this.
So maybe one day.

\section{Java}
Java is an~object-oriented language with syntax similar to C and C++, but it
omits many of the~features that make C and C++ complex, confusing and
unsafe~\cite{JVM7Spec}.
Originally it has been developed by James Gosling and Sun Microsystems and its
purpose was to address the~problems of building software for networked
consumer devices~\cite{JVM7Spec}.
Now Java is maintained and developed by Oracle. It is in its major version 7. Lately Java
developers are focusing on filling the~gap between Java and other languages in
some specific areas. For example auto closing of resources in try-catch blocks,
new IO concepts which allow programs to use features of file systems like hooks,
permissions and other parts of the~nice project Coin\footnote{Project Coin is
a set of adjustments and improvements of Java language.}.

\subsection{Interpretation and JVM}
Vital fact about Java is that it is interpreted language.
Program is compiled into byte code which is then executed on the~Java Vritual
Machine or JVM. JVM is an~abstract computing machine. Implementation of the
JVM varies between platforms and processor architectures but the~contract stays the~same. This allows the~program to be
fully portable including the~file system handling. The~Java virtual machine
knows nothing of the~Java programming language, only of a~particular binary
format, the~class file format. a~class file contains Java virtual machine
instructions, the~bytecode, and a~symbol table, as well as other ancillary
information~\cite{JVM7Spec}.

The interpretation system brings several very important benefits to the~game.
First was already mentioned - portability. Second one is stability. JVM stands between
the program and OS. Any bogus memory management, invalid commands or any other
mess is mostly caught by JVM and is not passed to the~system. Program then fails
with exception (or can be recovered in some cases) and developer gets nice
stacktrace containing valuable information. This can spare him of some long
nights. 

\subsection{Optimization}
In the~case of code being optimized in the
compilation time compiler must take some decision about optimization techniques
without knowing anything about real usage profile of the~program. On the~other
hand HotSpot\footnote{HotSpot is a~JVM implementation from Oracle.} has JIT or
Just-in-time compilation and adaptive optimizations in the~hand to optimize and
adapt based on the~runtime conditions. Interpreting the~byte code rather than
just executing machine instruction can be slower this is without doubts. That's
why some highly exposed parts of the~code gets compiled to the~native
instructions during the~runtime. Other important optimization is inlining of
methods. This applies mostly to getter and setter but can be applied generally
to any method. Calling method to access the~member of some class is correct from
the object-oriented point of view. If it comes to the~instructions counting it
is better to access directly. JIT takes care of this issue by inlining of the
method in the~runtime if it is accessed often. Amount of optimization and
threshold values for optimizations can vary between different settings of JVM. HotSpot VM runs
in either server or client mode. First one is much more optimization aggressive
because up time of the~application is expected to be long so the~ratio of time
spent optimizing to time spent running will be good. Second one is less
aggressive because it expects to run application on the~user computer, maybe some
small tool. Spending seconds optimizing it and then using it for one minute is
not the~desired goal. For example default threshold for the~compilation into the
native code is 10,000 invocations of the~method. This can be of course changed
and it is very interesting to play with this and find out how much our
applications can gain from usage of this state of the~art
VM~\cite{javaMagazine:introductionToJIT}.

\subsection{Garbage Collection}
Last thing I~want to go deeper into about Java is the~Garbage Collection.
Probably everybody who came near the~Java programming language heard that he doesn't have
to take care about allocated memory releasing. This is partially true but those
who want to program somewhat seriously in Java should dig deeper because the
statement above is not completely true. To support my statement I~will point out
that recognizing when the~object (or group of objects) is eligible for garbage
collection is a~significant part of the~SCJP\footnote{Sun Certified Java
Programmer, now renamed to Oracle Certified Professional, Java SE 6 Programmer}
certification test.
Second thing worth exploring is garbage collection itself and methods used. Very good
reading about this topic is~\cite{Wilson:1992:UGC:645648.664824}. Recently G1 -
the new exciting HotSpot VM garbage collector - became the~official parallel GC
for production use and it is definitely something to read about
~\cite{Detlefs:2004:GGC:1029873.1029879}.

\section{Conclusion}
Three languages mentioned above were selected because they are object-oriented
and we can call them higher\footnote{Languages are described as being high/low
level or something between by the~amount of the~abstraction they offer.
Low-level languages require detailed knowledge of the~environment for which the~program
is designed. High-level languages provide a~lot of abstraction from the
details of hardware and OS implementation.} although C++ allows both high-level
and low-level approach. This is important because it is said that using the
object-oriented language developer can be five to fifteen times more effective
than when he use low-level language. Programming in the~high-level language is
also less prone to errors~\cite{dokonalyKod}. All of them are very well documented
and offer a~lot of examples as well as third party documentation. There is a~lot
of frameworks and libraries available for all of them.

The .NET framework has been removed from the~selection because it is not
portable, at least not at this moment. From the~Java and C++ I~have chosen Java to be the
programming language of this project. One reason is portability. Although C++ is
available on both Microsoft Windows and Linux platforms writing one code that
can be just recompiled for other platforms is possible but rather challenging. Java offers
this feature out of the~box. There is one drawback in using Java and it is
access to the~native resources. To be able to use Java I~had to come with
solution to this issue and it is Java feature called JNI.

JNI or Java Native Interface is a~part of Java which allows developer to call
from Java code to the~C or C++ code and back. This API is very well documented
and allows to implement very small routines for HW access in C or C++ and call
them easily from the~Java program and process results back in the~Java code.
This actually gives the~developer possibility to take the~full advantage of the
Java platform without any restrictions of interpreted
language~\cite{Liang:1999:JNI:520155}. I~will go into more details of JNI in the~appendix~\ref{A:chap:JNI}.

There was one more plus for the~Java language. I~have been actually using Java
on the~daily basis for six years now together with a~lots of frameworks. My
familiarity with Java allows me to take full advantage of the~resources and
functions available. Different authors varies on this topic. Some of them say
that that developers are about 30\% more effective using a~language that they
are familiar with~\cite{dokonalyKod}. Others say that for each project the~best
suitable technology should be selected despite of the~lack of
developer's knowledge on the~language or framework.
I think that there is something on both approaches but from my experience I~know
that the~first project done by using a~new technology always struggles a~bit, so
I went with the~first group and incorporated those 30\% into my decision.

So Java it is!

\chapter{Frameworks}
\label{chap:frameworks}
The good selection of the~suitable framework can bring only benefits to a~project.
Wrong selection can mean a~disaster to the~whole idea. In the~previous text I~pointed
out two needs of the~project. It must be easily extendable and its UI must be
generally easy to use. These two needs are little bit more connected as it may
seem.
If you want to have extendable application you have to consider placing of new
functions into the~UI. Of course you can go with some sub-menu which loads its
content based on contributions. Well this might work but it is not user friendly
a bit to have all additional action hidden in some menu. On the~other hand
preparing every possible place in the~UI for extensions means considerable
amount of work and success is not sure, because one will definitely forget one
the most important place.

So there is actually need for two frameworks, some that can handle easy
contributions and extensions. Second is some widget\footnote{Widget toolkit is a~set of widgets for use in designing applications with graphical user interfaces (GUIs).%
} library that provides rather
standard set of UI elements and preferably offers a~native skin.

Actually there is already a~GUI widgets library incorporated in the
Java as a~part of Oracle's Java Foundation Classes aka JFC. I~personally do not
find Swing library so fancy. Even if it provides native look and feel on MS Windows,
on Linux it doesn't come with very good support of standard dialogs and look. So library
that would provide native look and feel.


\section{Eclipse Platform and Rich Client Platform}
\label{sec:EclipsePlatformAndRCP}
The Eclipse platform is an~extensible open source development platform. It can
definitely be called a~Framework while there is a~very robust basic
implementation, which is fast and reliable on the~top of which you can build
your application.

It employs plugins with declarative connections between each other in order to
provide all of its functionality on top of the~runtime system, which is in
contrast to some other applications where functionality is typically hard coded.
The runtime system is based on Equinox. Everything in 
Eclipse is a~plugin, except the~runtime system.

\subsection{What is Eclipse RCP}
The Eclipse Rich Client Platform (RCP) is a~minimal set of plugins
necessary to build a~rich client application on the~top of Eclipse Platform. The~RCP is composed from the~following components.
\begin{itemize}
  \item the~standard bundling framework Equinox OSGi.
  \item the~core platform which takes care of booting Eclipse and running
plugins.
  \item the~Standard Widget Toolkit (SWT) a~portable widget toolkit. We will
  get back to this one.
  \item JFace which brings MVC%
  \footnote{MVC - Model View Controller design pattern%
	} programming pattern into the~SWT.
	\item And last but not least the~Eclipse
Workbench which brings views editors perspectives and all the~window
management~\cite{wiki:eclipse}.
\end{itemize}  

You may noticed that there is a~very important connection between Eclipse RCP
and Eclipse Platform. We can even say that Eclipse RCP ``stands on'' the~Eclipse
Platform. It is important to realize that Eclipse RCP is nothing else than a~set
of plugins which contains and offer some functionality. RCP doesn't add anything
to the~basic core parts of the~Eclipse Platform.

In the~further text I~will mention basic features and benefits of the~Eclipse
Platform and RCP.

\subsection{OSGi}
Since version 3.0 Eclipse Platform is built in the~fashion of the~OSGi
container. We will now talk about OSGi for a~while.

Some sources describe it as a~module system and service
platform for the~Java programming language that implements a~complete and
dynamic component model. Applications or components (coming in
the form of bundles for deployment) can be remotely installed, started, stopped,
updated and uninstalled without requiring a~reboot~\cite{wikiOSGi}.

Now OSGi moved far beyond the~original purpose and one of the~main
and most complex implementations is Eclipse Platform. Well it is a~little bit
more tricky than that, but we will go through it. 


\subsubsection{What is OSGi Bundle}
OSGi bundle is a~basic structural component of the~whole system. It is a~simple
JAR\footnote{JAR is a~zip file which aggregates many files into one. It is
usually used to distribute Java classes and other resources~\cite{wikiJAR}.} file
which contains besides usual classes and resources also a~manifest file. 

Name of this file is \texttt{MANIFEST.MF} and it contains important information
about dependencies, exported packages, native code and a~lot of other information
which are necessary for the~bundle to be integrated and then loaded.
The example of an~OSGi bundle manifest from~\cite{wikiOSGi} can be seen in
algorithm~\ref{alg:manifest}.

\begin{algorithm}                      % enter the~algorithm environment
  \caption{Example of an~OSGi Bundle Manifest}
  \label{alg:manifest}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true]
	Bundle-Name: Hello World
	Bundle-SymbolicName: org.wikipedia.helloworld
	Bundle-Description: a~Hello World bundle
	Bundle-ManifestVersion: 2
	Bundle-Version: 1.0.0
	Bundle-Activator: org.wikipedia.Activator
	Export-Package: org.wikipedia.helloworld;version="1.0.0"
	Import-Package: org.osgi.framework;version="1.3.0"
\end{lstlisting}     
\end{algorithm}



OSGi bundle (and also an~Eclipse Plugin which we will talk about later) has
following stages of the~lifecycle.
\begin{enumerate}
  \item INSTALLED
  \item RESOLVED
  \item STARTING
  \item ACTIVE
  \item STOPPING
  \item UNINSTALLED
\end{enumerate}

In the~stages \texttt{STARTING} and \texttt{STOPPING} a~hook can be registered
and then called at the~right point to perform some action. This hook can
possibly load and unload resources, do some connections to the~DB or check the
configuration. Whatever it is it may not take a~long time, because it can cause problems with loading
application due to timeouts.

\subsubsection{Equinox}
Equinox is an~Eclipse project that provides a~certified implementation of the
OSGi R4.x core framework specification~\cite{wikiEquinox}. First occurrence of
this project inside the~Eclipse Platform was in the~version 3.0. OSGi
specification from that time wasn't sufficient so there were some changes.
These changes were then incorporated into the~``R4.x'' version of the~OSGi.

You can actually include any OSGi compliant bundle into your Eclipse application
while you are using Equinox. Eclipse is the~OSGi container since 3.0 version.
(Current stable version in the~time of writing this article is 3.6 and version 4.0 is in
the alpha stage.)

\subsection{Eclipse Plugin}
\label{subsec:eclipsePlugin}
Eclipse plugin is the~basic element of the~Eclipse application. Every Eclipse
application consist from the~set of plugins. Some of them may be shipped with
the platform and some of them might be a~part of your application, but it is
still just a~plugin. 
\subsubsection{How Is It Loaded}
At the~very beginning of the~application start, loader checks which plugins
should be loaded\footnote{You may specify it manually or you can specify just
some plugins which will take care of dynamic loading of all plugins in the
specific folder. Details of this behavior are beyond the~scope of this article}
After that order of plugins based on dependencies is resolved (assuming that
there are not cycle dependencies) and then bundles are loaded. You can get a~picture of the~lifecycle using the~list of stages in the~previous Chapter.

Inside a~plugin you can have something called \texttt{Activator}. This class
must extend \texttt{org.\-eclipse.\-core.\-runtime.\-Plugin} class and \texttt{void
start\-(\-org.\-osgi.\-framework.\-Bun\-dle\-Context)} and \texttt{void
stop(\-org.\-osgi.\-framework.\-BundleContext)} methods are called when
the~bundle is entering \texttt{STARTING} or \texttt{STOPPING} stage.

\subsubsection{Plugin Content}
Eclipse plugin is basically an~OSGi bundle and as such it contains the~bundle
manifest, java classes, additional resources like translation files,
configuration files, libraries and practically anything
developer might want to have available in the~deployment. But there is even more. Besides the
\texttt{MANIFEST.MF}, Eclipse plugin can contain also \texttt{plugin.xml} file.
This file specifies extensions and extension points of the~plugin.
We will get back to this concept later.

Your plugin can contain resources which will not appear in the~final build
version of the~plugin. a~good example of these resources are source bundles for
libraries. You can link source to the~jar library which you download from the
Internet. But you definitely don't want to have source file which is twice
bigger than library itself deployed to the~build for customers. This is driven
by \texttt{build.properties} file located in the~root of the~plugin. Description of
this file is far beyond this article. If you need some detailed information on
this, go to the~online help of Eclipse. You will find all you need there.

\subsubsection{Motivation To Create Plugins}
Motivation to create plugins is very similar to the~motivation to create
packages. It makes your application easier to understand and maintenance costs
go directly down. 

In the~plugin development there is more to gain. While plugin is the~smallest
unit which can be delivered to the~build you can manage content of your application easily
when there are specific plugins for specific functions. After a~while you will
probably have a~set of plugins which are used in every application you build.
And as we all know code reuse is a~good thing.

\subsection{Eclipse Fragment}
\label{subsec:eclipseFragment}
Eclipse fragment is something very similar to the~plugin, but there are important differences.

Fragment cannot be used as standalone unit. It has to have its host plugin.
Purpose of the~fragment is to expand classpath of the~host plugin. It may sound
confusing, but we will go through some examples to explain it. The~structure of
the fragment is similar to the~plugin, but it contains fragment.xml instead of
plugin.xml file.
\subsubsection{Reasons To Create Fragments}
Example is better than a~thousand words so let's have one. 
You created a~plugin which contains some functionality. Let's say it contains
something that can print ``Hello'' into some file on the~disk, but to make
it fancy you decided that the~text will be translated into the~locale of the
user.
To accomplish this goal, you prepared five different files in the~bundle having
following name convention \texttt{localeCode.hello}. 

But lately you received a~lot of emails from people from China where they
complain that there is no Chinese implementation. You really don't want to
rebuild this plugin every time new file has to be added. Instead of that you can create fragment which expands the~host plugin.
In this case it is your Hello plugin. In the~fragment you can place file
\texttt{zh.hello} which will contain something like ``ni
hao''.

Then you send this file to China and instruct users to place it next to the
plugin. After the~restart of the~platform (or possible just your plugin), there
will be also Chinese available.

Important thing to realize is that plugin doesn't know anything about fragments.
It only extends the~classpath in runtime. So you can imagine it as adding that
file into the~original plugin.

Of course you can understand that this example was trivial. But now you can
imagine application which has millions of translatable strings and you want to
deliver new language. This way you just make those fragments available for each
plugin which needs to be translated.


\subsection{Eclipse Feature}
Eclipse feature is a~way of grouping and describing different functionality that
makes up a~product. Features do not contain any code.  They merely describe a~set of
plug-ins that provide the~functionality for the~feature and information about
how to update it~\cite{eclipseHelp}.

One interesting thing about features is that feature can include other features.
We will get back to the~advantage of this behavior later in the~builder section.

Features are packaged in a~feature archive file and described using a~feature
manifest file, feature.xml. The~example of a~feature.xml from~\cite{eclipseHelp}
follows in algorithm~\ref{alg:feature}.

\begin{algorithm}[H]                % enter the~algorithm environment
  \caption{Example of a~Feature Definition}
  \label{alg:feature}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true]
<?xml version="1.0" encoding="UTF-8"?>
<feature
      id="org.eclipse.platform"
      label="%featureName"
      version="3.3.0"
      provider-name="%providerName"
      image="eclipse_update_120.jpg">

   <description>
      %description
   </description>

   <license url="%licenseURL">
      %license
   </license>

   <url>
      <update label="%updateSiteName" url="http://update.eclipse.org/updates/3.3"/>
      <discovery label="%updateSiteName" url="http://update.eclipse.org/updates/3.3/">
   </url>

   <plugin
         id="org.apache.ant"
         download-size="0"
         install-size="0"
         version="1.6.1"/>

   <plugin
         id="com.jcraft.jsch"
         download-size="0"
         install-size="0"
         version="0.1.31"
         unpack="false"/>
	...
</feature>
	
\end{lstlisting}
\end{algorithm}

\subsubsection{Reasons To Create Features}
In the~previous example you may noticed the~update url part. That is one of the
most important advantages of using features. Of course you can directly download
and deploy plugins manually. But that is not the~most comfortable way how to do
that. You can create an~update place, which contains latest versions of your
features in the~specific structure. Anyone using Eclipse RCP application, which
has update feature integrated, can add your feature and plugins which are
contained in this feature simply by filling the~path to your update site. The~rest of the~project is then automatic. Dependencies are examined and in the~case
they are satisfied, you can proceed with the~rest of the~installation.

This system is mostly used to deploy features intended for the~existing
applications. Good example is Eclipse IDE itself. There are thousands of plugins
which can be directly installed into your IDE. This can be anything you can
imagine. You can install anything from FindBugs to LaTeX support through this
system.

Lately new Eclipse Marketplace was created. It is something which should replace
previous installation system in the~future. It is very similar to the~Synaptic
bundle installer or any other Linux features installation component. Something
which can be considered similar is also iTunes Marketplace. In the~Eclipse
Marketplace, you can place any piece of software you create and let other people
download it and use it. You may even charge for the~download or make your
available as a~shareware.

Previously described attribute of a~feature that it can include other features
into itself can be used when creating the~application builder. Builder topic
itself would take a~lot of pages so I~will point out just some basic reasons why
including other features may be interesting.

When you use Eclipse building feature you can select that your application is
based on plugins or features. If your choice is plugins, you have to specify
each plugin separately. But if you select feature, you just specify one main
feature of the~application. This feature then contains all other features from
which application consist. If you have only one small project with a~short
lifecycle this doesn't make a~lot of difference to you. But if you have several
applications which share some functionality, let's call it ``commons'', you may
want to have some commons feature which contains bundles of functionality. It
could be logging, hibernate, basic utils or any other. You can just include
these features into the~main feature of the~application and every change in the
commons features will be taken into build instantly, because it is just a~link
to the~real commons features.

If you would create commons feature for each application or you would specify
commons plugins for each project, you can end up with a~lot of description files
which are obsolete.


\subsection{Extensions}
\label{subsec:extensions}
At the~very beginning of this article word ``declarative'' was used. Now I~am going
to explain why this framework can be described as declarative and what a~giant advantage it is.

Declarative in this case means that you can turn the~dependencies around and you
can have a~clear code without a~lot of code which loads additional
functionality. And from my point of view the~really big thing is possibility to
avoid those if-else statements which should hide functions for some specific
customers.

I guess everybody who has created some serious piece of software which was used
by more than one customer ended up in the~situation when one customer wanted
some additional functionality and it would be inappropriate to show this
functionality to other users.

Fortunately concept of Extensions and Extension Points solves this issue
completely. For example you have a~menu in the~application where actions are
shown. You created a~special action for one customer. Because you are
experienced Eclipse developer, you separated this functionality into the~special
plugin. But now you need to add the~action to the~menu. In the~classic Java
world you would have to go to the~menu code and you would have to add another
button wrapped by if-else code to show it only to the~proper customer. But this
would require dependency on the~special plugin. It means that new plugin would be tightly coupled to the~rest of the~application.

BUT we can go the~other way around and define extension point for the~menu. In
the declaration of this point we would say something like this. Everybody can
give me something what they want to have in the~menu, but it has to meet following
contract (which can be the~interface, abstract class, resource or even just a~string).
Then in the~code where the~menu is created you just ask the~platform for all the
contributions into you extension point and now you can iterate over items you
received and render them into the~menu.

Using this approach you can include menu item into the~special plugin and just
contribute it to the~proper extension point where you want to have your button.

We can go far beyond this. You can for example contribute settings for log4j.
Using this principal every plugin can setup separate settings of log4j for
logging of its own classes. At the~point of configuration of log4j you just load
all the~settings, merge them and apply them. There could be thousands of
use-cases when using this concept is much more effective than using the~usual
way. We can call this loose coupling.

Of course that there are moments when using the~extensions is useless or even
problematic, but after a~while good developer is able to identify these places
and avoid them. I~know it is hard to let your brain which is trained in the
classical approach accept this idea but after you will, you will be rewarded
with a~huge potential of creating extensible
applications which are cheap and have great maintainability.

On the~other hand there are also drawbacks to this approach. While you can not
tell who is contributing at the~compilation time, you cannot control the~number
or the~order of contributions. So if you want to use some code of
some plugin you have to accept all contributions this plugin makes.
It can for example contribute an~action to the~menu bar. It is usually
undesirable in your specific application. You just wanted some nice small class
but you ended up with five actions in the~menu.


\subsubsection{Extension Point}
Using a~metaphor of electrical outlets, Extension point can be compared to the
socket. You specify the~contract which has to be met for you to be able to use
the incoming extension.

Extension point is defined inside the~plugin.xml (or even fragment.xml) file.
You should also specify an~extension point schema which describes rules of the
extension point. Extension point is usually defined using the~extension point
wizard in the~Eclipse IDE, because it is definitely not easy to do it by hand.

Here is one more example which can help you to deeply understand the~concept.
You can specify an~extension point that will say ,,I will let you know when
somebody pushes the~button''. Then long after delivering the~product to the~
market you can just add a~new plugin which will contribute to this
extension point and this plugin will be notified after pushing the
button without changing the~original code.

Examples of the~extension point and the~schema follow in
algorithms~\ref{alg:extensionSchema} and~\ref{alg:extensionPoint}.
You may notice in the~schema that there are two extension points. One of them is for resources (text
files) and the~other one is for classes which implement some specific interface.

\begin{algorithm}[H]               % enter the~algorithm environment
  \caption{Example of an~Extension Point Schema}
  \label{alg:extensionSchema}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=Java]
...
   <element name="properties">
      <complexType>
         <attribute name="resource" type="string" use="required">
            <annotation>
               <documentation>
                  
               </documentation>
               <appinfo>
                  <meta.attribute kind="resource"/>
               </appinfo>
            </annotation>
         </attribute>
      </complexType>
   </element>

   <element name="propertiesProviders">
      <complexType>
         <attribute name="class" type="string" use="required">
            <annotation>
               <documentation>
                  
               </documentation>
               <appinfo>
                  <meta.attribute kind="java" basedOn=":com.mediasol.commons.log4j.cfg.Log4JConfigProvider"/>
               </appinfo>
            </annotation>
         </attribute>
      </complexType>
   </element>
...   
\end{lstlisting}
\end{algorithm}

In the~example of plugin.xml of the~plugin containing the~schema you can see how
extension point is declared and also two immediate contributions into this
extension point. So this file stands for something like I~offer the~point for
adding a~configuration of the~log4j in the~one of two forms. And there are default
configurations already contributed.

\begin{algorithm}[H]                      % enter the~algorithm environment
  \caption{Example of an~Extension Point Declaration}
    \label{alg:extensionPoint}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=Java]
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
   <extension-point id="configurations" name="Log4J Configurations" schema="schema/configurations.exsd"/>
   <extension
         point="com.mediasol.commons.log4j.configurations">
      <properties
            resource="basicLog4j.properties">
      </properties>
      <propertiesProviders
            class="com.mediasol.commons.log4j.cfg.WSConfigProvider">
      </propertiesProviders>
   </extension>
</plugin>
\end{lstlisting}
\end{algorithm}

\subsubsection{Extension}
Extension can be then compared to the~electrical plug. You have something you
want to place somewhere. You make sure that it follows contract given by the
extension point schema and you are good to go.

You have to have a~dependency on the~plugin into which you want to contribute.
It may be also useful to mention that if you are contributing a~class, reader of
the extension point will most probably try to instantiate it. Therefor the~class
you are contributing has to have public non-parametric constructor. If you want
to pass some information to the~class you may want to create method init of some
kind which will be called immediately after the~instantiation.

The example of the~extension was mentioned in the~previous paragraph and I~think that it was sufficient to understand how to contribute. Be sure that you will be
creating extensions using the~UI editor because there is a~lot what can go wrong
if you decide to go by yourself.


\subsection{Building an~Application}
We will just peep under the~hood of building, because as I~mentioned before it
is very complex topic.

Basically you have two ways how to build and pack your application. First is
using the~IDE and exporting your product. Well I~should mention what the~product
is. It is a~file which describes your application on the~level of packing it
together. It says from which plugins of feature it consist, what should be the
name of the~executable file, what are icons, what parameters should have JVM
running your application and much more.

This file might seems like a~good way to go. For the~one man show project it
probably even is. Problems can come when you invite few more people to the
project and you want to create automated builder. Unfortunately automated
builder of the~Eclipse IDE doesn't work with the~product file.

If you have something called Delta Pack you can even build for other platforms
than the~one you are developing on. Delta pack is a~set of fragments for each
important plugin of the~Platform which has some platform dependent content. For
example native parts of the~framework, resource manager, UI libraries and
others.
At this point you should be already familiar with fragments and what are
benefits of this approach so we can move back to the~product file. You simply
ask to export you application. Compiler will compile all the~classes and exporter will bundle proper resources, plugins,
fragments and all other necessary parts for your application together with
parts of Eclipse Platform which are suitable for the~target platform for which you are building.

The other way is to use ANT\footnote{Apache Ant is a~Java library and
command-line tool whose mission is to drive processes described in build files
as targets and extension points dependent upon each other~\cite{ANT}.} build
which is also available. In this case you have to create a~lot of ANT files, properties files and complex structure. 
But the~result can be with some luck automated builder, which downloads latest
source from CVS, compile it, execute additional tasks such as GWT\footnote{GWT
stands for Google Web Toolkit} UI build for example and then pack it for all
targets platform you want to use. After that it notifies you by mail and uploads
results to the~FTP server.
\subsection{Application deployment}
Eclipse application is deployed as a~folder structure containing some native
launcher in the~root together with some config files. It depends on the
JVM\footnote{Java Virtual Machine} available on your system. There are few ways how to point the~launcher to the~specific JVM but these are beyond this article. The~useful thing
might be delivering the~JVM bundled together with the~application. While
Eclipse application perfectly hides that it is running on the~superb language called
Java and it is using great Hot-Spot JVM you may want to play along. You really
don't want to bother users with instructions about obtaining and installing the
latest JVM and you don't want to read bug reports how your application doesn't
work properly on the~JVMs which you never heard of. You can bundle your own
JRE\footnote{Java Runtime Environment} to the~\texttt{jre} folder of your
application and native launcher will automatically prefer this one. And you can even instruct the~builder to do it by itself. All
you really have to do is to point out paths to JVMs for different target
platforms.

There are other specific things you may want to do with your application during
deployment. Useful thing is that every feature can contribute to the~root
folder of the~deployment and that these contributions can be driven by target
platform. Using this concept you can deploy shell scripts or additional .bat and
.exe files to run your application as Windows Service.

\subsection{Eclipse 4}
\label{subsec:Eclipse4}
When the~development of the~software was already ongoing, new version of Eclipse
with codename Juno was released. Juno was the~first GA\footnote{General
availability} release of the~new 4 series. This series brings CSS-based styling,
more flexible UI layouts and makes it easier to create applications with look
different from IDE. It also brought service-oriented programming into the~game.

The great improvement of the~platform and of its possible utilization is a~new
concept of pluggable presentation engine. Series 4 holds an~internal structure
of the~workbench in the~EMF\footnote{Eclipse Modeling Framework} model. This model
is translated into widgets using presentation engine API. Default presentation
engine that renders the~model using traditional SWT widgets is included in the
platform~\cite{eclipseR4}. The~benefit is, that presentation layer can now be changed
easily to deploy to totally different environment including web browser.

Because the~first stable release of Juno project was available at
27-Jun-2012 when the~development was already ongoing, I~decided not to switch
this project to the~new platform as it might hurts the~development rate and
bring new issues. The~release plan of this project is tight and any new
unpredicted troubles can spoil it.

\section{NetBeans Platform}
\label{sec:NetBeansPlatform}
Eclipse Platform and RCP described earlier has one major competitor. It is
NetBeans platform. NetBeans platform is developed by community and sponsored by
Oracle. It is used as a~platform for advanced JDK\footnote{Java Development Kit}
tools including VisualVM\footnote{Tool delivered within JDK which allows users
to monitor running JVMs, debug them, compare performance, do the~memory
analysis and many others} and some others. It is a~background of NetBeans IDE,
which is a~popular tool for, but not limited to, Java development.

NetBeans use standard Swing visual library which comes with Java. It implies
non-standard look on most of the~OS. Both platforms are an~implementation
of OSGi R4 container. Both have huge community, almost unlimited reading
resources and training available. 

From my point of view there is one big
difference between these two. NetBeans is driven by Oracle and it is a~single
project. Eclipse on the~other hand is developed by community with many
heterogenous projects going on. In my eyes, this makes Eclipse to be a~true
open-source project while NetBeans are a~project with open source.

On the~website of NetBeans one can read a~comparison between NetBeans Platform
and Eclipse RCP~\cite{netBeansCompare}. I~find this article misleading, based on
outdated information and designed to favour NetBeans over Eclipse rather than to
bring objective result of comparison. To point out few of these, Eclipse comes
with UI Designer called WindowBuilder which is very flexible and also
bi-directional which allows editing of hand-written UI code. It supports Swing,
SWT, RCP and others. Another misleading information is that Eclipse has only
proprietary build system. Fact is, that it offers its building system PDE. It is
basically a~set of Ant scripts and project Tycho supports complex building using
maven. I~think one can get the~picture about accuracy of the~information
provided in this comparison.

\section{Conclusion}
Some people like to build their own frameworks to replace something that works
perfectly and is already available. They do it for different reasons. Some
because they think they can do a~better job. Some because they just don't want
to be dependent on other people choices. Well I~am not one of them. I~don't like to reinvent the
wheel so I~am excluding any possibility of preparing my own framework or of not
using one from the~architectural decision.

In the~previous pages I~have described Eclipse Platform and RCP in the~late 3
series. I~have also pointed out new series 4. NetBeans platform was briefly
described in the~text with comparison to the~Eclipse RCP. Both are so similar
that the~reasoning between them is very subtle and is mostly dependent on other
factors than features and capabilities.

I have chosen to use Eclipse RCP series 3 for following reasons. Eclipse offers
advanced system of contributions and extension points as described in the
previous text. This allows developer to invert dependencies and to create
software in very modular fashion with significant impact on decoupling. Second
reason is described in section~\ref{sec:NetBeansPlatform} and it is a~nature of
the Eclipse Project and Eclipse Foundation and its open-source approach. Last
but not least is my deep knowledge of Eclipse Platform and RCP which allows me
to take advantage of framework capabilities up to its limits. Reasoning for
series 3 over series 4 of Eclipse Platform is described in
\ref{subsec:Eclipse4}.

\chapter{IDE}
\label{chap:IDE}
Choose of the~integrated development environment can be vital for the~result of
the project.
IDE should support the~developer and provide him with tooling that can make his
job easier.
\section{Requirements}
\label{sec:IDERequirements}
The IDE should provide easy code navigation such as ``go to declaration'', ``go
to implementation''. Listing of all calls to the~method. Exploring the
inheritance tree and others. This navigation features are useful in day-to-day
usage of the~IDE. Exploration of unknown, possibly third party code, is the
point where one can use the~full potential of these navigation features . Then
we enjoy quick listing of all calls to a~method so we can explore how is it used in other parts of code. It is also useful when
we refactor the~code so we can estimate impact of the~change to the~rest of the
code quickly.

Code suggestion and completion together with pre-built constructs can speed up
code writing. Customizable code templates should also be available. It should be
capable of adding file headers with licensing info, create stubs of classes,
getters, setters. It should be able to automatically create a~template of loops,
try-catch clauses and others.

Good IDE comes with the~integrated debugging support. Stepping together with
variable views, watches, conditional breakpoints are the~vital parts. Good
stacktrace navigation is also very useful.

Advanced code refactoring is a~must have in the~modern programming. While most
of the~programming techniques including Agile programming and Test Driven
Development suggest short development cycles with lots of refactoring taking
place, developer should have proper tools available in the~IDE. Examples of the
refactoring tasks that should be integrated are interface extraction, superclass
extraction, method extraction, constant extraction, conversion of local variable
to field. Renaming of all kinds including local variables and methods and
methods reordering. Method signature manipulation with default input values can
be useful.

If the~developer has these tools at hand and knows how to use them properly, he
will create cleaner code which will be less error prone. He will be willing to
spend few minutes cleaning the~class after the~development is finished and
targets are met, because it is easy and it can save him some time when he or
somebody else will be revisiting the~class in the~future.

Capability of running some kind of code analysis for possible errors and code
style should be available either built-in or using third party tools such as
FindBugs or CodeStyle.

Last but not least is a~support of the~framework in use. Developer should be
able to manage declarative elements using some automated tools to avoid errors
from misspelling. Declarations verification can be also useful.

\section{Eclipse IDE for RCP and RAP Developers}
Eclipse IDE is actually built on top of the~Eclipse RCP platform by adding a~set of plugins and features which provide the~IDE capabilities. This makes it
ideal for the~Eclipse RCP development. It comes with the~advanced Java
Development Tools including complex refactoring, code completion and code
templates.
Wizards that automate processes of new elements creation are a~vital part of the
development tooling. It can show errors, warnings and information directly in
the source code together with the~suggestions for fixing which can be run in
batches. This can be particularly useful during the~refactoring. This feature
can look ordinary but there is more in it. Eclipse comes with its own Java
compiler which can compile or at least verify parts of source files which
wouldn't compile as a~whole unit. This results into properly marked errors in
one method when there are some more errors before in the~source file.

Eclipse IDE comes with the~variety of tools for Eclipse RCP and Plugins
development including but not limited to Plugin wizards, bundle manifests
editors with automated processes. Notable is the~UI editor for the~product
definitions which allows one to declare all the~necessary information for
building a~complete product in few easy steps. It can also export the~complete
installation bundle by few clicks.

Eclipse IDE contains much more than described in the~section
\ref{sec:IDERequirements}. It comes with integrated Git support, FindBugs
support, advanced code analysis and even \LaTeX~IDE is available.

My deep knowledge of this environment is very significant for the~proficiency of
the development. It is suggested that one should use one environment for one
task and he should know it thoroughly to use all its features up to full
potential~\cite{pragmaticProgrammer}.

\chapter{Analysis and Design}
\label{chap:aandd}
In this Chapter, I~will describe main use cases of the~project to present the
core of the~processes executed by the~user. In this part integration of future
extensions will be also described as one of the~main goals of this project is to
provide extensive capabilities of extensions.

Capabilities and possibilities of the~selected framework will be described in
the context of provided parts, design guidelines and provided existing pieces
that can be reused.

Small excursion into the~UI Design of application will be presented. UI is the
contact point between the~user and the~project and bad UI decisions can
discourage newly coming user from further exploring of the~application although
it can bring him benefits and values in the~long term. Decisions will be put
into context of the~framework UI design guidelines.

Last but not least we will go through is the~structure of the~application, its
division into parts and through the~most important part - extendability of the
project.

\section{Basic Use Cases}
\label{sec:basicUseCases}
In this section I~will go through the~description of basic use cases of this
project.
\subsection{Creating a~Session}
\label{subsec:creatingASession}
There should be a~simple wizard available to guide the~user through the~process
of basic Session parameters setup. These parameters can be the~name and
description but can be extended in the~future. Good example of future extensions
would be a~name of the~author.

This wizard and every other in the~application should validate the~input to
prevent user from submitting invalid or bogus values and to guide him through
the process.

\subsection{Manipulating a~Device in the~Session}
The Device is actually the~vital part of the~Session configuration. At the~end
most of the~instructions and action flows end in some kind of Device.

Session should provide easy way of adding a~Device. This process should start
with the~Device selection. After the~Device is selected it should continue by
the Device dependent wizard where the~Device is properly set up.

It should be possible to revisit the~configuration of the~Device without need to
remove it and add it again to reconfigure it.

User should be able to see the~list of Devices assigned to the~Session.

\subsection{Manipulating a~Module in the~Session}
It should be possible to easily add a~new Module to the~Session. Application
should provide facilities to configure the~Module if needed. Module should be
able to show the~list of Devices it needs to function properly in some form.

\subsection{Manipulating a~ Monitor in the~Session}
Requirements for the~Monitor are very similar to the~Device and Module. It
should be possible to add it, configure if needed. Monitor as well as Module
should be able to provide the~information about required Modules or at least
about missing Modules that prevent the~Monitor from functioning properly.

\subsection{Manipulating a~Program in the~Session}
It should be possible to add a~Program to the~Session and to configure its
environment. One aspect that is different from the~Monitor, Module and Device is
that the~Program some text file stored in the~workspace of the~application. On
the other hand Monitor, Module and Device describe virtual objects or objects
that might exist physically but are not a~part of the~application workspace.

Therefore when adding a~Program to the~Session, it should be possible to select
existing Program or to create a~new one in the~selected location in the
workspace of the~application.

It should be possible to easily navigate from the~Session configuration to the
physical location of the~Program source code or to the~editor where the~user can
work on the~Program.
\subsubsection{Internal Scripting Language}
While the~application should be as modular as possible, users and contributors
are free to provide implementation of any program languages they like. The~application should come with at least one predefined language for users to be
able to start using the~application without the~significant effort of
implementing own language.

The language I~prepared for this application is very simple and very verbose
scripting language, which operates on the~common pool of variables and does not
contain function or methods at this point. Functions can be on the~other hand
compensated by calling other scripts which will make changes to the~common
variable pool. The~biggest benefit of this language is the~fact that it is very
easy to implement new functions. Only thing that has to be done is to implement
the interface which consist of four methods from which three describe number of
parameters and name of the~function. This interface is then contributed using
the extension point and contributions system described in
\ref{subsec:extensions}. More information on the~scripting language are
available in the~documentation.

\subsection{Session Validation}
\label{subsec:sessionValidation}
Session should provide facility for validation so the~user can easily see which
Modules Devices and other parts of the~Session signal some problems without the
need to actually run the~Session. This is a~vital part of the~user experience
with the~framework. With this approach he doesn't need to run the~Session until
it fails, then fix the~problem and run it again in this iterative manner. He
will rather fix all problems that can be found before runtime and then he will
proceed with the~runtime testing.

This validation should be presented in the~form of markers or list of issues
with references.

\subsection{Running a~Session}
It should be easily possible to run the~Session, preferably by one click. This
process can be similar to the~programming IDEs. Running the~Session should
provide console feedback. This can again be in the~similar fashion to running
any program in the~debug mode in any IDE. It should be possible to preserve the~output in some kind of log.
While some Monitors can provide visual feedback to the~user it should be
possible to view these feedback windows as well. It should be possible to
recognize whether the~Session is still running or it finished.

The process of running a~Session should be blocking. It means that during the
execution of one Session, user should be able to work freely in the~application.
This is useful requirement while some Sessions might take a~long time to run.

\subsection{Manipulating Console Logs}
While Session execution should be able to produce logs for further examination,
user should be able to access the~logs from within the~UI of the~application in
some form of a~log viewer.

It should be possible to delete logs that no longer carries any value.

\subsection{Organizing Sessions, Results and other artifacts}
Sessions, results and any other artifact that might be useful should be
organized into the~hierarchy of projects in the~workspace of the~application. Using this
approach user will be able to work on more project simultaneously without the
need to exit or reload the~application.

It should be possible to export existing projects into the~filesystem,
preferably in the~form of zip file, to be able to transfer projects between
different workspaces and machines. This of course leads to the~requirement of
importing existing projects into the~workspace.

\subsection{Future Extensions Integration}
On several occasions in this Chapter, I~mentioned the~need of
Device/Module/Monitor/Program specific wizard or actions. Because this project
is intended to be highly modular it is necessary to provide good integration of
further extensions in the~context of UI. Each Device might have different needs
of configuration thus unified configuration wizards cannot be used. Each
extension should be free to provide own dialog for configuration and
initialization to fully utilize its capabilities.

\section{Framework capabilities and its Benefits}
\label{sec:frameworkCapabilites}
Concepts of the~Eclipse Platform and Eclipse RCP are described deeply
in~\ref{sec:EclipsePlatformAndRCP}. Concept of extension points and contributions brings many benefits into the~design and implementation of UI. One benefit is a~kind of natural implementation of the~observer
pattern~\cite{HFDesingPatterns.Observer}. Observer pattern follows the~Hollywood
principle and brings the~loose coupling into the~game. 

In the~traditional application schema, when implementing a~toolbar one would
have to list all the~actions that will be shown on the~toolbar. After few
months new feature is requested and developers must change the~toolbar
implementation to add a~new shortcut. This will happen over and over during the
lifespan of the~product. It brings very tight coupling into the~design. What's
more it requires endless changes to one point of the~program which grows as the
application grows and this is really not a~good practice.

Observer pattern on the~other hand can be described by ``Don’t call us, we’ll
call you''. Observer usually injects some implementation of handler or event
callback to the~class that is being observed. This way the~subject doesn't even
know about the~observer and at the~certain point he just notifies all the
observers about the~event. This concept screams	 ``Loose coupling'' all over
the place. If we unleash our imagination a~bit we can fit this pattern to the
loading of the~toolbar described in the~previous paragraph. Let's say that
loading of the~toolbar is the~event and interface of the~observers requires them
to return what they'd like to have (contribute) to the~toolbar. Every time
toolbar is reloaded, each component of the~system can contribute its action
without the~toolbar implementation ever knowing what to load in the~compilation
time.

Extension points and contributions take this even further. Modules do not need
to know how to register for the~certain ``event'' programmatically. They just
implement the~interface and injection is done using declarative extensions. Now
this I~call loose coupling. We can now extend the~idea from toolbar to any other
part of the~UI and not just the~UI. Any part of the~application that is expected
to be extended can use this concept and everybody who wants to deploy his
functionality into the~application just declare it and that's it.

On the~other hand there is also a~few disadvantages of this great concept.
When you design your application you have no clue about the~count and nature of the
extensions to come so it can break the~UI design.

You cannot disallow any contribution. When you want to use only a~small portion
of a~plugin you have no way of disabling its contributions so it can add
undesired functionality to your application. Only way around is to change the
source code of the~plugin if allowed by the~licencing policy.

There is no steady order of contributions. Although contributions are usually
loaded in the~same order this can change and one cannot make any assumptions
about it. Thus it is hard to design order of actions in menu, toolbars or any
other place. There are some facilities like weights, designated areas of
extensions and some more but these have limited capabilities.

\subsection{Workbench}
Eclipse Workbench User Guide describes workbench as following. ``The term
Workbench refers to the~desktop development environment. The~Workbench aims to achieve seamless tool 
integration and controlled openness by providing a~common paradigm for the~creation, 
management, and navigation of workspace resources.

Each Workbench window contains one or more perspectives.  Perspectives contain views 
and editors and control what appears in certain menus and tool bars.  More than one 
Workbench window can exist on the~desktop at any given time.''~\cite{EclipseHelp.Workbench}

If we translate this, workbench encapsulates all the~views, editors,
perspectives, controls, menus and everything else you can think of into one
consistent bundle. Important part of the~description states that it provides
common paradigm for actions. This dramatically changes the~learning curve of any
software that is based on Eclipse RCP. There is a~set of guidelines or
considerations called RFRS (Ready for Rational Software). This considerations
describe how to design the~application to follow the~best practices of
Eclipse RCP applications\footnote{Most of the~products created by Rational
Software are based on Eclipse RCP and IBM is one of the~most important
contributors into the~Eclipse Platform and RCP}.

 
\begin{figure}[h!]
  \centering
  \includegraphics[width=\textwidth]{../misc/workbench/workbench}
  \caption{Preview of Eclipse RCP Workbench}
  \label{fig:workbench}
\end{figure}
See figure~\ref{fig:workbench} for better understanding of what is editor,
view, workbench and perspective.

\subsection{View}
A view is a~visual representation of data or an~action. It can represent state
of certain virtual object and manipulate it (for example Variables View in the~IDE)
or you can imagine a~style panel in the~text processing editor.

Views can be attached to the~editor in the~editor area and its state and react
on the~changes of the~content of the~editor. Variables view was an~example of
view which doesn't react on changes in the~editor area. Java class outline view
on the~other hand changes as you type your Java code or when you change the
focus to a~different Java class.

It can be chosen if only one instance of the~view might exist or multiple
occurrences are allowed. It doesn't make much sense to have multiple instances of
Variables View. On the~other hand multiple Console views each attached to the
different running process might be a~benefit.

\subsection{Editor}
An editor area is usually located in the~middle of the~layout. It can hold
multiple editors opened. Different editors can be assigned to the~different file
types. For example when you open Session by double-clicking it in the~navigation
view, it opens associated Session Editor. On the~other hand if you double-click
script file, it will be opened in the~proper script editor. 

Multiple editors can be opened at once, but only one of them can be active.
Views, actions and menus react to the~selection of the~active editor and offer
proper actions and information.

Editor area supports different layouts of editors. Basic is a~stack layout as
shown on figure~\ref{fig:workbench} but there might be two editors next to each
other opened or any other possible combination.

\subsection{Perspective}
Eclipse Workbench User Guide describe Workbench as follows. Each Workbench
window contains one or more perspectives.
A perspective defines the~initial set and layout of views in the~Workbench window. Within the~window, 
each perspective shares the~same set of editors. Each perspective provides a~set 
of functionality aimed at accomplishing a~specific type of task or works with 
specific types of resources. For example, the~Java perspective combines views 
that you would commonly use while editing Java source files, while the~Debug 
perspective contains the~views that you would use while debugging Java programs~\cite{EclipseHelp.Perspective}.

\subsection{Existing Components}
Eclipse RCP and other available plug-ins offer huge amount of ready to go
components that can be used in the~application based on RCP.

In my application I~will try to use as much of them as possible while users of
any other application based on Eclipse RCP are used to them. Navigator component
will be used to navigate through the~workspace of the~application and to
manipulate the~resources. It offers standard extension points for actions that
can take place on different resources as well as ``New'' wizards and many
others.
Standard menu actions like About dialog, Save, Save All, Close, Open and others will be
used. Console view will be used for the~output of Session execution and standard
text editor can be used for log viewing and script editing.

\section{UI Design Decisions}
While attractivity of the~UI can play serious role in success or failure of the
project, I~invested some time into it to follow best practices in the~UI
design.

The scope and time span of the~project doesn't allow me to do the~full UI
analysis so I~picked some parts of it which I~think are the~most beneficial in
this case and apply them.

During the~design of the~GUI, I~have created several UI prototypes -
mockups\footnote{The mockup is an~example of the~application UI that can
be evaluated or tested without the~need to actually create the~backend
capabilities. It can range from very simple paper made screens to complex
simulations with partial functionality of the~product.} - to be able to evaluate
benefits and find issues with the~UI decisions before I~spend valuable time and
resources on creating full implementation. It is also valuable as a~reference
manual for the~UI coding and for evaluation with potential users. Some of the
mockups are mixed into the~text, for example figure~\ref{fig:setup} on
page~\pageref{fig:setup} or figure~\ref{fig:newScriptProgramWizard} on page~\pageref{fig:newScriptProgramWizard}.

\subsection{Personas}
While there are no resources for quantitative analysis or experiments of any
kind, I~decided to create two personas as a~representation of expected common
users. I~based the~UI design on needs of these two samples. It will be helpful
in the~alpha testing to verify the~possibility to
achieve goals defined in use cases~\ref{sec:basicUseCases} by both personas.

\subsubsection{Persona 1 - John}
\begin{itemize}
  \item Male, 25 years old.
  \item Student of the~Computer Science.
  \item Uses the~platform for the~School project.
  \item Has advanced knowledge of computers and common UI elements.
  \item He is not willing to invest time into finding shortcuts.
  \item Prefers descriptive menus or obvious ways of achieving goals.
  \item Successful result is the~measure, he doesn't care much about the
  progress.
  \item He will use the~application mostly in the~default settings.
\end{itemize}

\subsubsection{Persona 2 - Carl}
\begin{itemize}
  \item Male, 30 years old.
  \item Hobbyist, computers background.
  \item Uses the~platform to drive his own projects.
  \item Has advanced knowledge of computers and common UI elements.
  \item He is working with the~application in the~long term.
  \item Willing to take time in searching the~optimal ways.
  \item Prefers keyboard shortcuts and reloadable configuration as he often
  repeats tasks.
  \item He wants to be informed about every step and detail.
  \item He will prefer flexible settings.
\end{itemize}


\subsection{Results of the~Persona Analysis}
\label{subsec:resultsOfThePersonaAnalysis}
Personas described above have two opposite approaches to the~products. To sum it
up first one is looking for easy achieving of the~goal in the~short term. The~second one likes to play with things and he is looking for the~long term suitable tool.

This fact brings me to the~decision that the~application should provide both
advanced more flexible and simple predefined ways whenever possible. This can be
achieved for example by keyboard shortcuts and wizards that provide advanced
settings at the~end of the~process and can finish early with default advanced
settings and others.

	\begin{figure}[h!]
  \centering
  \includegraphics[width=\0.4\textwidth]{../misc/dummyDeviceInitialCfg/dummyDeviceInitialCfg}
  \caption{Mockup of the~Initial Configuration of the~Dummy Device}
  \label{fig:dummyDeviceInit}
\end{figure}
	

\subsection{General GUI Guidelines}
There is lot of methods of GUI evaluation and perspectives on how to design most
usable UI. To name few Heuristic evaluation, Cognitive walkthroughs, Standards
inspection and many others~\cite{Nielsen:1994:UsabilityInspMethods}.

The one I~think is a~best fit for this occasion is the~heuristic evaluation
backwards. It is normally used to evaluate existing GUI designs. Why not to turn
it around and use the~metrics of the~evaluation for the~GUI design itself.
Heuristic evaluation process by J.Nielsen provides list of ten heuristics to be
applied on the~UI. In the~following paragraphs, I~will cite the~guideline by J. Nielsen together with the~description of how it is
implemented or met in the~application~\cite{Nielsen:10heuristics}.

\subsubsection{Visibility of system status}
The system should always keep users informed about what is going on, through
appropriate feedback within reasonable time. 

This guideline is mostly matched by the~standards Eclipse Workbench itself. When
running a~Session, console output and stop button availability give decent feedback on the
state of the~execution.

\subsubsection{Match between system and the~real world}
    the~system should speak the~users' language, with words, 
    phrases and concepts familiar to the~user, rather than system-oriented 
    terms. Follow real-world conventions, making information appear in a~
    natural and logical order. 
    
    While this application is focused on the~technical people, it speaks the
    technical language. Objects in the~problem domain model are design to follow
    objects in the~real world and to follow the~principal of the
    technology stack common for example to the~Device drivers.
    
\subsubsection{User control and freedom}
    Users often choose system functions by mistake and will need some
    kind of a~clearly marked "emergency~exit" to leave the~unwanted state
    without having to go through an~extended dialogue. Support undo and redo. 
    
    While Eclipse RCP guidelines and standard dialogs follow this rule, Session
    dialog will not support undo and redo in the~first version and this is good
    point of future extension.
    
\subsubsection{Consistency and standards}
    Users should not have to wonder whether different words, situations, or 
    actions mean the~same thing. Follow platform conventions.
    
    Unlike the~other Java GUI platforms, SWT takes advantages of the~standard UI
    components and for the~common operations like Open, Save As, Print and many
    others uses standard system dialogs rather than some custom made dialogs.
    This allows users to interact with components they are familiar with.
    
\subsubsection{Error prevention}
    Even better than good error messages is a~careful design which prevents a~
    problem from occurring in the~first place. Either eliminate error-prone 
    conditions or check for them and present users with a~confirmation option 
    before they commit to the~action. 
    
    Implementation of this approach is briefly mentioned in the
   ~\ref{subsec:creatingASession} and~\ref{subsec:sessionValidation}. Each
    wizard as well as Session editor provides error checks and validations prior
    to the~action execution which allows user to prevent errors from occurring in
    the~runtime of the~action execution.
    
\subsubsection{Recognition rather than recall}
    Minimize the~user's memory load by making objects, actions, and options 
    visible. The~user should not have to remember information from one part of the~
    dialogue to another. Instructions for use of the~system should be visible or 
    easily retrievable whenever appropriate. 
    
    This concept is held by JFace dialogs and wizards as well the~design of the
    Session editor.
    
\subsubsection{Flexibility and efficiency of use}
    Accelerators -- unseen by the~novice user -- may often speed up the~interaction 
    for the~expert user such that the~system can cater to both inexperienced and 
    experienced users. Allow users to tailor frequent actions. 
    
    Nature of this guideline was briefly mentioned in the
   ~\ref{subsec:resultsOfThePersonaAnalysis}. One of the~typical users will
    expect more verbose and longer way which is visible and offered. The~more
    experienced one will want to learn shortcuts use them to be more efficient.
    Some of the~steps to achieve this goals are described in the~mentioned
    paragraph.
    
\subsubsection{Aesthetic and minimalist design}
    Dialogues should not contain information which is irrelevant or rarely needed. 
    Every extra unit of information in a~dialogue competes with the~relevant units 
    of information and diminishes their relative visibility. 
    
    This guideline is useful and makes sense but in the~context of the
    application which is very technical and must provide a~lot of information of
    which most is useless until something goes wrong, I~will take no special
    steps to achieve it. On the~other hand I~will try to minimize the
    information that cannot be helpful in the~context of the~action or step
    being performed.
    
\subsubsection{Help users recognize, diagnose, and recover from errors}
    Error messages should be expressed in plain language (no codes), precisely 
    indicate the~problem, and constructively suggest a~solution.
    
    While most of the~errors that can occur will come from programs created by
    the~users, this guideline seems to be out of the~reach in the~original
    framework design. All the~parts of the~system which are under control of the
    original framework will follow this guideline and API for the~extensions
    will be designed to provide as helpful error messages as possible.
    
\subsubsection{Help and documentation}
    Even though it is better if the~system can be used without documentation, 
    it may be necessary to provide help and documentation. Any such information 
    should be easy to search, focused on the~user's task, list concrete steps to 
    be carried out, and not be too large. 

	Application comes with built-in help that can be context-sensitive. It means it
	can automatically offer part of the~help which is relevant to the~action being
	performed. It also offers concept of cheat sheets. Cheat sheet is an~	interactive step by step manual of how to achieve certain goal. User can
	perform the~operations or he can have the~cheat sheet to perform it. This is a~	very good substitution of the~getting started guide.
	
	\begin{figure}[h!]
  \centering
  \includegraphics[width=\0.6\textwidth]{../misc/newScriptProgram/newScriptProgram}
  \caption{Mockup of one page of the~New Script Program Wizard}
  \label{fig:newScriptProgramWizard}
\end{figure}
	
\subsection{Framework Guidelines}
As mentioned earlier Eclipse RCP comes with the~set of
guidelines which describe best practices and commons usage of the~UI elements
in the~Eclipse RCP based applications. In the~further text I~will mention some
of them which applies or are important for the~application. Although a~little
outdated, the~list can be found at ~\cite{EclipseWiki.UIGuidelines}. List of
interesting picks follows.

  \paragraph{Error Handling} 
When an~error occurs which requires either an~explicit user input or immediate attention from users, communicate the~occurrence with a~modal dialog.
  \paragraph{Dialogs - Initializiation} 
When a~dialog opens, set the~initial focus to the~first input control in the~container. If there are no input controls, the~initial focus should be assigned to the~default button.
\paragraph{Browse Buttons}
Use a~Browse Button whenever some existing object is referenced by any wizard.
\paragraph{Wizard Completion}
If a~new file is created, open the~file in an~editor. If a~group of files are
created, open the~most important, or central file in an~editor. Open the~readme.html file upon creation of an~example project.
\paragraph{Unsaved Changes}
If the~resource is dirty, prefix the~resource name presented in the~editor tab
with an~asterisk.

Benefit of properly applying these rules is seamless learning curve for users
who have previous knowledge of any application built on the~Eclipse Platform.

\subsection{Decisions}
\label{subsec:decisions}
Conclusions of the~persona analysis~\ref{subsec:resultsOfThePersonaAnalysis}
suggest that application should provide both basic visible ways to conclude actions as well as advanced shortcuts and aids
for advanced users.

Framework itself provides great concept of commands and handlers which fits this
goal perfectly. Command is an~abstract notation of something that can happen
whatever that is. One command can have multiple handlers. Handler takes care
about real execution of the~command. These handlers state availability rules
based on the~current selection, state of the~application and many others. Only one handler is available for one command at a~time. Command
can have a~default handler.

Command can have key bindings assigned. These key bindings can be changed by the
user. Key biding can be assigned to the~certain state of the~application or
selection only. This concept allows same key sequence to be assigned to
multiple commands on different circumstances.

Once command and its handler or more handlers are created, one can assign them
to the~different places of the~application. For example to context menus
of existing components, toolbars, menus, key bindings and some others. This assignment is
purely declarative based on the~contributions system of Eclipse Platform. 

Now you can see why commands and handlers are perfect for creation of
applications which provide basic as well as advanced access to actions. Action
can be placed into the~menu as a~basic solution. Adding advanced shortcuts is
then only a~matter of declarative definitions.

Besides basic - advanced concept, I~will stick to the~common rules of Eclipse
RCP applications design procedures and guidelines as well as to the~general
guidelines of the~GUI design.

\begin{figure}[h!]
  \centering
  \includegraphics[width=\textwidth]{../misc/setupMockup/setup}
  \caption{Mockup of the~Session Setup Editor}
  \label{fig:setup}
\end{figure}

\section{Structure of the~Application}
Eclipse applications are divided into plugins. Plugin is a~smallest deliverable
item of the~whole application bundle. Plugins can be grouped into features and
features can be then delivered and updated easily through several existing
Eclipse facilities.

For the~namespace of plugins I~will use my domain called
\texttt{zarubsys.\-net}.
Plugins that are or will be shared between my applications will be in the
namespace of \texttt{net.\-zarubsys.\-commons.*}. Plugins that are specific for
this project will be in the~namespace of
\texttt{net.\-zarubsys.\-robotplayground.*}.

General idea is to decouple the~backend part of the~UI implementation so the
Programs and Sessions itself can run in the~headless mode. To be able to simply
distinguish between the~UI and backend implementation, plugins containing UI
will be in the~namespace of \texttt{net.zarubsys.robotplayground.gui.*}. These
plugins shouldn't contain any business logic of the~application nor core
features. These are supposed to conain only GUI wrapping backend functionality.
In the~other words, backend plugin should never have dependency to the~GUI
plugin.

\subsection{Division into Parts}
As stated in the~previous text, some part of the~project called commons will be
shared with other projects. Commons will encapsulate useful libraries for
example logging facilities and real util classes for Strings manipulation and
others. It will contain implementation of the~scripting language as well because
other projects may benefit from it.

Project specific plugins will be divided into the~core which will contains vital
parts of the~application all the~interfaces to be implemented by extending
Modules and basic or dummy implementations where appropriate.

As the~core is the~basic part of the~backend, basic GUI plugin will be provided
as a~cornerstone of the~UI itself. It will contain basic perspective definition,
workbench layout definitions, icons etc.

Session GUI plugin will extend the~UI cornerstone to add Session manipulation
facilities. It will take care about Session creation, editing of the~Session
and of adding new content to the~Session. To be able to execute the~Session, GUI
running plugin will be provided. It will take care about Session execution, console logging and any other action related
to the~execution of Session.

Plugins or modules listed above will be the~complete core of the~application.
Everything from this point will be an~extension although provided in the~default
application bundle.

\subsection{Extending Modules}
Following list of extending components will be a~part of the~basic
application bundle. Some more may come but these will be out of the~context of
this thesis for now.

\begin{itemize}
  \item Scripting language implementation of Program.
  \item Dummy Device which will hold its position and direction.
  \item Module for the~Dummy Device which will move the~Device and rotate it.
  \item Virtual obstacles Module which will provide obstacles on the~map.
  \item Obstacles Monitor which will monitor collisions between Dummy Device and
  virtual obstacles.
  \item Joystick Device and Module which will implement basic joystick
  capabilities for moving Dummy Device on the~map and much more.
\end{itemize}

\section{Project Management Tools}
The size of the~project described in the~previous text might be compared to the
small business application. And it should be treated the~same way. Code should
be available in the~version control facility. There should be one place where
downloadable binaries will be available. It should have its bug tracking system
even if now it is just one developer. It can be useful for keeping track of
features to be done and bugs to be fixed as well as for reporting of bugs and
feature requests from the~public. Some kind of wiki or other facility for
installation and updating guidelines should be available.

While this project is licensed under the~LGPL licence I~had variety of free
project management solutions available. I~have selected the~Google Code hosting
because I~have a~good experience with it from my bachelor thesis and some other
projects.

Google Code offers free hosting for free software. Services of this hosting
consists of Git repository, bug tracking system, wiki, downloads, customizable
home page and user management. Using this publicly known and accepted services I~will be able to provide good support of the~product in the~future or pass or
share the~project to some other developer if needed.

This project is available on the~url
\url{http://code.google.com/p/robot-playground/}.


\chapter{Implementation of the~Core}
\label{chap:implementationOfTheCore}
Implementation of this project took a~significant amount of time and its code
can be considered extensive for the~project of this size. We cannot clearly
describe here all the~implementation details, but we will focus on the~most
important parts and parts where some non-trivial tweaking was required to
succeed.

As mentioned in Chapter~\ref{chap:IDE} Eclipse IDE for RCP and RAP Developers
was used as the~IDE for the~implementation in its 3.7.2 version code named ``Indigo
SR2''. Target platform was selected as ``Running Platform" which means that
a set of plugins that are used for running the~IDE are use to provide
plugins necessary to start the~application being developed. Version 3.7.2 is
the last one of the~3 series and it is expected to be supported for quite some
time.
\section{Eclipse Product}
\label{sec:EclipseProduct}
As described in~\ref{subsec:eclipsePlugin} plugin is the~smallest deployable
unit\footnote{Except of the~Fragment which is not runnable as a~standalone
bundle and must always be attached to some plugin.} of the~Eclipse based
application. To be able to build an~application, product defining plugin must be
created and it must contain the~product defining file. The~name of this plugin
in this product is \texttt{net.\-zarubsys.\-robotplayground.\-gui}. The~GUI
suffix comes from the~fact that this is a~GUI build of the~application. In the~early
stages of the~development, headless application was built in order to test
capabilities of the~core implementation. Product defining file is located in the
root of the~product defining plugin and describes what implementation of
\texttt{IApplication} should run when this product is started. It also states
name of the~application, its icons, launcher screen, native launcher name. It
can specify parameters of the~application per each platform and it can even
specify and bundle specific JRE to avoid necessity to bother end users with
Java installation and to enforce proper version. 

The most important part of
the product defining file is the~list of dependencies. It can be defined either
per plugin or per feature. While this product will not be updated via P2
repositories, features are not necessary and it is defined using plugins. Set of
application plugins is selected and IDE can then compute required dependencies and add them to the~list.

When I~mentioned \texttt{IApplication}, I~should also point out that the
implementation of this interface must be contributed into the~extension point
\texttt{org.\-eclipse.\-core.\-runtime.\-application}. Only then it can be
selected in the~product editor. The~implementation takes care about start of the~UI loop and
saving of the~preferences when application is closed.

Other important and usual part of the~Eclipse Application product defining
plugin are subclasses of following three classes and one implementation of the
interface.

\subsection{WorkbenchAdvisor}
\label{subsec:workbenchAdvisor}
Subclass of this class is used when creating the~workbench in the~UI loop
initialization. It provides configurations and settings to be used for the
workbench creation, windows selection and default perspective declaration.

While reusing project navigator component which will be mentioned later, I~found
that some icons are not properly display inside this component. After some
research I~found out that some other plugin which is not a~part of my
application provides images for the~navigator. This is clearly an~flaw in the
modularity concept but I~had to fix it in my application. The~fix appeared to be
easy declaration of the~images from the~subclass of the
\texttt{WorkbenchAdvisor} in the~\texttt{initialize(IWorkbenchConfigurer)}
method. Sample of the~fix code can be found in Algorithm~\ref{fig:imageBugFix}.

\begin{algorithm}                      % enter the~algorithm environment
  \caption{Image displaying bugfix}
  \label{fig:imageBugFix}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=Java]
@Override
public void initialize(IWorkbenchConfigurer configurer) {
	configurer.setSaveAndRestore(true);
	super.initialize(configurer);
	IDE.registerAdapters();
	final String ICONS_PATH = "icons/full/"; //$NON-NLS-1$
	final String PATH_OBJECT = ICONS_PATH + "obj16/"; //$NON-NLS-1$
	final String PATH_WIZBAN = ICONS_PATH + "wizban/"; //$NON-NLS-1$
	Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH);
	declareWorkbenchImage(configurer, ideBundle,
			IDE.SharedImages.IMG_OBJ_PROJECT, PATH_OBJECT + "prj_obj.gif", true);
	declareWorkbenchImage(configurer, ideBundle,
			IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT + "cprj_obj.gif", true);
	declareWorkbenchImage(configurer, ideBundle, IDEInternalWorkbenchImages.IMG_DLGBAN_SAVEAS_DLG, PATH_WIZBAN
		      + "saveas_wiz.png", true); //$NON-NLS-1$
}

private void declareWorkbenchImage(IWorkbenchConfigurer configurer_p,
	Bundle ideBundle, String symbolicName, String path, boolean shared) {
	URL url = ideBundle.getEntry(path);
	ImageDescriptor desc = ImageDescriptor.createFromURL(url);
	configurer_p.declareImage(symbolicName, desc, shared);
}
  \end{lstlisting}     
\end{algorithm}

\subsection{WorkbenchWindowAdvisor}
Application should declare a~subclass of this class because its methods get
called on the~strategic points of the~application window lifecycle. One method
that is most probably always implemented is \texttt{preWindowOpen()}. In this
method shape of the~window, its title and presence of the~toolbar, status bar,
menu bar and other parts can be altered. Other methods are for example
\texttt{postWindowClose()}, \texttt{postWindowRestore()} and more.


\subsection{ActionBarAdvisor}
Subclass of this class is where all the~default actions shown in the~toolbar and
menu are created. Most of the~actions are common actions available from the
platform. These are for example Quit, Show About Dialog, Save, Save As, Open,
New and others.

Action should be registered into the~platform first and then it can be used on
many places around the~application. Methods where this should happen are kind of
obvious. These are 
\texttt{makeActions(IWorkbenchWindow)},
\texttt{fillMenuBar(IMenuManager)} and
\texttt{fillCoolBar(ICoolBarManager)}.

Minimalistic example of Save As action shown in main menu and in the~toolbar is
presented in the~Algorithm~\ref{fig:SaveAsAction}. Other actions are deployed
in the~similar fashion.

\begin{algorithm}                      % enter the~algorithm environment
  \caption{Save As action registration and deployment into menu and toolbar}
  \label{fig:SaveAsAction}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=Java]
private IWorkbenchAction saveAsAction;

@Override
protected void makeActions(IWorkbenchWindow window) {
	saveAsAction = ActionFactory.SAVE_AS.create(window);
	register(saveAsAction);
}

@Override
protected void fillMenuBar(IMenuManager menuBar) {
	IMenuManager mainMenu = new MenuManager("Main", "robotPlayground");
	mainMenu.add(saveAsAction);
	menuBar.add(mainMenu);
}

@Override
protected void fillCoolBar(ICoolBarManager coolBar) {
	IToolBarManager toolbar = new ToolBarManager(coolBar.getStyle()|SWT.BOTTOM);
	coolBar.add(toolbar);
	ActionContributionItem saveAsCI = new ActionContributionItem(saveAsAction);
	toolbar.add(saveAsCI);
}
  \end{lstlisting}     
  
\end{algorithm}

\subsection{IPerspectiveFactory}
\label{subsec:IperspectiveFactory}
Purpose of the~perspective factory is to provide initial layout and content of
the Perspective. Every Eclipse Application should have at least one perspective.
This fact can be even hidden from the~user but still perspective is there on the
background.

Perspective should have some ID and should provide an~implementation of
\texttt{create\-Initial\-Layout(IPageLayout)} method. In this method decision
whether editor area will be visible is made. Initial visible views and their
position are determined. Positioning of views is made easy and flexible by
relative specification such as
\texttt{layout.addView("net.\-zarubsys.\-robotplayground.\-gui.\-navigator",
IPageLayout.LEFT, 0.25f, editorArea);} meaning that navigator view will be
located left to the~editor area and will cover 25\% of the~workbench window.
Perspective must be contributed to the~extension point
\texttt{"org.\-eclipse.\-ui.\-perspectives} to be able to use it even if it is a~default perspective.

\section{3rd Party Libraries}
There is a~lot of occasions when one want to add some functionality into the
project and this functionality has been already created by somebody and provided
in the~form of 3rd party library. While I~hate to reinvent the~wheel I~like to
take advantage of these libraries. There are two considerations to be made
before using library created by somebody else. For the~first is it licence
compatible with the~project? As the~second consideration, we should check that
the library is actively developed or maintained or at least the~source code is
available and licence allows us to do necessary changes to the~source.

There are three ways how to bundle external library into the~Eclipse
application. It can exist as an~Eclipse Plugin. In this case all we need is to
add it to the~target platform and add a~dependency to this plugin. Second option
is that it exists as an~OSGi bundle. While Eclipse application can run OSGi
bundles, the~procedure is similar to the~plugin option.

Last option is to create your own plugin and bundle the~library into this
plugin. Then export the~library packages so it can be used from plugins which
have dependency to the~library plugin. Library should be bundled together with
the source or the~source code can be linked to the~library from the~standalone
zip file. Anyway the~good rule is to bundle the~source code whenever available.

Library should be mentioned on three places in the~plugin definition. If it's
not it can lead to huge frustration because the~packages are not visible and
cannot be linked with other plugins.

\begin{itemize}
  \item On the~bundle classpath to be able to load it in runtime.
  \item In the~list of exported packages to be able to link to
  them\footnote{Not all of the~packages must be necessarily exported and
  sometimes internal packages or additional packages that are not of any use
  should stay hidden.}.
  \item It should be exported in the~java build path preferences of the~plugin
  (this is the~place where the~source code can be linked).
\end{itemize}

I personally prefer the~third option of how to integrate with 3rd party
libraries. Mostly because I~have full control about the~source code and version
of the~library provided.

\subsection{Log4j}
One important library I~integrate into the~most of my projects is
Log4j\footnote{\url{http://logging.apache.org/log4j/1.2/}}.
This library created by the~Apache Software Foundation provides easy and
flexible logging capabilities.
Logging can be setup in the~declarative fashion and can be changed in the~runtime. It can have
multiple appenders logging into console, into files and even through the~network
sockets.

It has very good performance results. On the~homepage of the~project they state
that ``On an~AMD Duron clocked at 800Mhz running JDK 1.3.1, it costs about 5
nanoseconds to determine if a~logging statement should be logged or not.'' I~think that this value is very low for the~project that doesn't need to run in
real time.

One good point about logging capabilities of Eclipse Platform based application
is that it provides method \texttt{eventLoopException(Throwable)} in the~class
\texttt{WorkbenchAdvisor} mentioned in~\ref{subsec:workbenchAdvisor}, which is
intended to be overridden in order to handle uncaught issues from the~application
loop. You just need to log the~throwable and that's it. Otherwise it might slip
unnoticed and can cause confusion when determining the~cause of the~issue.

\section{Core}
Until now we covered application and product definition with basic
initialization of the~windows and perspective together with logging. Now we can
get to the~real business of Core implementation. In the~following text I~will
describe in somewhat abstract fashion how the~core is implemented.

\subsection{Session}
Everything starts with the~Session. It is the~container that encapsulates the
definition of the~environment to be run. It is also capable of preparation of
the RunningSession. This preparation consists of the~instantiation (using
SessionsHelper) and initialization of all contained descriptors, Environment and
the API, verification of the~consistency and creation of the~container -
RunningSession, that can be used for execution of the~prepared Session.

RunningSession is used to execute the~Session and for holding of the~finished
state. Purpose of this class is to be able to easily manipulate and monitor
executed Sessions in the~multisession environment while each Session can be
executed multiple times concurrently. Each Program of the~Session is executed in
the separate thread to allow independent more modular Programs to be executed.

For monitoring of the~execution progress,
\texttt{IProgramFinishedListenerInternal} interface is introduced. Its
\texttt{notifiyFinished\-(IProgram<\-IProgramConfiguration>)} method is called
every time some Program thread finishes its execution. Default implementation of
the interface \texttt{IProgramFinishedListener} is passed to each thread
together with all other added instances. These can be added to
the~Session by \texttt{addProgramFinishedListener\-(IProgramFinishedListener)} method. This
concept handles concurrency issues.

Although it was mentioned in the~analysis, Session itself doesn't hold instances
used in runtime. It holds id of the~Module, Monitor or any other part and its
configuration. All the~actual Modules and other elements are instantiated when
RunningSession is prepared.

\subsection{Environment and API}
\label{subsec:EnvironmentAndAPI}
Environment is the~class that is used to interconnect instantiated parts of the
Session. Every Module Monitor or other element has access to the~Environment and
can use it to communicate with the~application or any other part of the~Session. Right now
Environment supports logging utilities, messages or notifications population and
halting of the~execution process. This halting capability is based on the
implementation of IStopListener interface by any part of the~Session.
Environment itself is expected to be a~subject of a~change.
It is intended to grow with the~grow of the~whole application as the~functionality is extended.

Environment provides access to the~instance of the~API class. API an~access
point for the~Program to call methods of internal Modules. While it is
accessible via Environment any other part of the~Session can get its hands on a~Module and call functions on them. Although it lowers a~measure of encapsulation
and single responsibility principal, it permits existence of macro Modules which
delegates calls to Modules they depend on. Using this approach we trade
encapsulation for modularity and extendability.

API is instantiated during the~preparation of the~RunningSession and it has
information about all Modules and Monitors as well as about Environment. It's the~actual
backend of the~notifications population. Functions calling is done by delegation
to the~Module for the~given id if it is found.

\subsection{Session Parts Configuration}
Although each part of the~Session has its particular interface to be implemented
they have one thing in common. Each part of the~Session except of the
Monitor must be configured after the~instantiation. Each part type provides its
own configuration interface and requires implementation of the~interface to be
passed. What's more each part is parametrized by the~configuration class to be
able to write clean code on expected subclass of the~configuration interface.
Empty implementations of configurations are provided rather than to pass null
value.

\subsection{Modules}
Each Module must implement method with the~following signature \texttt{Object
callFunction\-(String functionName, List<Object> values)} from
the~\texttt{IModule} interface. Depending on the~Module nature, this can be
simple switch statement or complex methods provisioning. For the~comfort of creation of new Modules, AbstractModule was
created.

AbstractModule provides facility for function calls to be dispatched to proper
methods based on the~methods annotations. If a~method has \texttt{Function}
annotation present, it is added to the~methods cache during the~instantiation of
the AbstractModule. Function description is loaded from this
annotation. Parameters of each annotated methods are read.
Each parameter must be annotated with \texttt{Param} annotation. Name of each
parameter is loaded from this annotation. Parameter name \texttt{return} is
reserved for the~real return parameter of the~method. Information whether null is a~valid
value to this parameter is also contained in the~annotation. Null is prohibited
by default.

By putting all this information
together FunctionDescriptor is created. It consist of the~method name,
description, return parameter and list of parameters. Parameters are represented
by the~instance of \texttt{Parameter} class. This class provides easy way of
checking if passed object is compliant with the~nature of the~parameter.

AbstractModule provides method for registration of any method in order to
provide functionality by composition rather than by inheritance. For this
purpouse instance information contains map of invocation objects to be able to
invoke method on other instance than the~one which directly inherits
AbstractModule.


\section{Script Program}
\label{sec:scriptProgram}
One of the~parts supplied with the~default bundle is the~Script Program. Script
Program is the~implementation of \texttt{IProgram} interface based on simple
scripting language developed for another project. I~have improved the~language
and changed the~calls resolving for the~late binding scenario.

\subsection{Script Parsing}

It consists of the~TokenReader which is able to read strings, function
identifiers and numbers and characters. This token reader is used by the
ScriptingEngine which runs as a~kind of state machine and is able to interpret
the data from the~token reader into the~call tree (it can be called AST -
Abstract Syntax Tree) which consist from ParsedStatement subclasses -
BlockStatement, FunctionStatement and ValueStatement. Each of this statements holds information about its position
in the~source file to be able to refer to it in case of any problems.

\subsection{Execution and Funtions Discovery}

Abstract method \texttt{Object execute(ScriptingEnvironment env)} is treated
differently in every subclass. Value statement basically just returns the~value
it holds. BlockStatement iterates through its children and execute them one by
one. Function statement is the~container that holds the~information about the
function to be called. In the~execution time it tries to locate function
implementation. If it fails to find it in the~register of internal functions, it
delegates searching to the~implementation of \texttt{IMissingFunctionHandler}
provided by the~scripting environment. Default implementation of this handler
throws error because it doesn't really have anything more to do. Custom
implementations can be plugged into the~environment to handle missing internal
functions in the~different fashion. This project passes the~function search to
the special handler, which instantiate function wrapper which will call the~API
to execute the~function. This way the~scripting language stays independent of
the usage in the~project and still it delivers required functionality.

\subsection{Variables Handling}

When one is executing the~script, he can prepare variable pools to be used by
the application. Each variable manipulation in this language refers to some
variable pool. It can be some special implementation or default MapVariablePool.
Every time value is assigned, read or removed from the~pool, this operation is
mapped to the~operation of the~simple HashMap. One Program can have multiple
variable pools. If uninitialize variable pool is used in the~Program, new
MapVariablePool is instantiated and used. At the~end of the~execution one can
access modified variable pools and act on the~result if required.

The concept of variable pool is primitive in some way but on the~other hand it
provides great flexibility and simple execution schema of the~interpreting
engine because it doesn't hold any information of the~current stack frame.

\subsection{Internal Functions}

Internal functions of this language are contributed implementations of
\texttt{IScriptFunction} interface which consist of four method. Three of them
state function name together with minimal and maximal count of parameters.
Fourth method is the~actual execution where the~action is performed. During the~usage
on previous projects many useful functions have been created. As of this moment
75 internal functions are provided. These cover functionality starting with
basic variable manipulation together with if statements and operations of
Boolean algebra. Cycles, sleep, error throwing, external script calling and
logging are also delivered as a~part of the~basic bundle. It is expanded by the
list manipulation functions, numbers handling and strings handling including
regular expressions matching capabilities. For this project I~added about 20 new
functions including sleep, while cycle, rounding to int, modulo operation.

Example of the~script usage follows in the~Algorithm
\ref{fig:scriptingLanguage}.


\begin{algorithm}                   
  \caption{Example of the~Script Program Language Usage (part of the~BFS
  searching)}
  \label{fig:scriptingLanguage}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true]
...
define('pool', 'currentNode', dequeue(value('pool', 'open'))),
define('pool', 'origin', getNodeOrigin(value('pool', 'currentNode'))),

if(and(not(isNull(value('pool', 'origin'))), greaterThan(getNodeOrthoDistance(createNode2D(dummyTelemetry.getX(), dummyTelemetry.getY()), value('pool', 'origin')), 0)), eval(
	define('pool', 'backtrackPath', 
		sublist(
			value('pool', 'backtrack'), 
			0,
			add(listIndexOf(value('pool', 'backtrack'), value('pool', 'origin')), 1)
		)
	),
	define('pool', 'backtrack',	
		sublist(
			value('pool', 'backtrack'),
			add(listIndexOf(value('pool', 'backtrack'), value('pool', 'origin')), 1)
		)
	),
	log('INFO', 'Backtrack - from: ', createNode2D(dummyTelemetry.getX(), dummyTelemetry.getY()), '; to: ', value('pool', 'origin'), '; path: ', value('pool', 'backtrackPath'), '; backtrack: ', value('pool', 'backtrack')),
	forEach('eachPool', 'node', value('pool', 'backtrackPath'), eval(
		define('eachPool', 'newDirection', getNodeDirection(createNode2D(dummyTelemetry.getX(), dummyTelemetry.getY()), value('eachPool', 'node'))),
		log('INFO', 'Backtrack step to: ', value('eachPool', 'node'), ', Direction=', value('eachPool', 'newDirection')),
		dummyMotion.rotate(substract(value('eachPool', 'newDirection'), dummyTelemetry.getDirection())),
		sleep(500),
		pushToList(value('pool', 'backtrack'), createNode2D(dummyTelemetry.getX(), dummyTelemetry.getY())),
		dummyMotion.move(1),
		sleep(1000)
	))
)),
...
  \end{lstlisting}     
  
\end{algorithm}


\section{Core GUI}
GUI plugins of the~core are annotated with the~\texttt{gui} suffix behind the
project name. Distribution of the~functionality into different plugins generally follows
the backend functionality distribution in order to allow separate bundling of
features in the~future if this requirement comes.

There is a~lot of GUI code in the~core of this project. In the~section
\ref{sec:EclipseProduct} we already covered how the~is the~product composed, how
is the~main window and its workbench initialized and we also discussed the
initial perspective. 

In the~description of the~GUI implementation I~would like
to talk about the~SessionEditor, its elements and the~great amount abstraction
that allows me to reuse the~same small portion of code to handle multiple types
of elements including their configuration. Next we will get to the~Program
wizard as it demonstrates some advanced capabilities of the~JFace wizards
framework. Last we will get to the~topic of running of the~Session while it
demonstrates perspective switching and built-in eclipse console
handling.

\subsection{Session Editor}
SessionEditor class is the~Eclipse editor which visualize Session and is capable
of its modifications. To be a~valid Eclipse editor the~class must extend
\texttt{EditorPart} class. To be able to be registered as a~default editor for
some file types it must be contributed to the~extension point
\texttt{org.eclipse.ui.editors}. The~snippet of the~contribution code can be
seen in the~Algorithm~\ref{fig:sessionEditorContribution}. From this moment
SessionEditor can be invoked using its ID or automatically based on the
registered filenames.

\begin{algorithm}                      % enter the~algorithm environment
  \caption{Contribution of the~SessionEditor editor}
  \label{fig:sessionEditorContribution}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=XML]
<extension point="org.eclipse.ui.editors">
	<editor
    	class="net.zarubsys.robotplayground.gui.session.editor.SessionEditor"
        default="true"
        filenames="*.session"
        icon="icons/newSession.png"
        id="net.zarubsys.robotplayground.gui.session.editor"
        name="Session Editor">
	</editor>
</extension>
\end{lstlisting}     
  
\end{algorithm}

SessionEditor class consist of usual methods which takes care of the
lifecycle of the~editor part, its saving and initialization. The~important part
comes in the~\texttt{public void createPartControl(Composite parent)} method
where the~UI part of the~editor is initialized. The~code consist of general
layout initialization and then from name and label editing elements. The~most
complex part is created by calls to four methods \texttt{createDevicesPart},
\texttt{createModulesPart}, \texttt{createMonitorsPart} and
\texttt{createProgramsPart}. Each of these methods is just few lines long and
its only purpose is to gather the~data objects from the~persistent Session and
delegate the~UI generation to one most important method
\texttt{createExpandingPart} together with the~information about objects to be
generated and nature of the~elements (Device, Module, Monitor and Program).

\subsubsection{System Objects GUI Abstraction Layer}
\label{subsubsec:GUIAbstractionLayer}

Before we proceed with the~further explanation of the~SessionEditor, let me
describe the~abstraction layer which encapsulates the~elements handing and
behavior. It consist of several interfaces, default abstract implementation and
helper class which provides access to the~registered implementations of the
interfaces.

Each element that is supposed to be available to the~Session editor must
implement the~basic interface \texttt{ISystemObject\-GUIProvider} and it must be
properly contributed to the
\texttt{net.\-zarubsys.\-robotplayground.\-gui.\-session.\-systemObjectGUIProviders}
extension point. The~interface provides access to the~general information about
the GUI behavior of the~system object as well as to the~manipulation methods. It
provides access to its image, description and also to the~invocation of the
configuration, adding or removal from the~Session and other methods.

Configuration, adding and removal from the~Session actually run some GUI code
rather than just providing the~guidelines or information to the~Session editor
itself. This way configuration of each element can differ significantly without
any need to inform Session editor about it. Adding to the~Session usually runs
some configuration wizard or dialog to be able to prepare proper implementation
of the~configuration for the~particular underlying system object.

Each provider represents one system object as described in section
\ref{sec:requiredFeatures}. So if one wants to provide new Module 
together with the~UI implementation, he should provide the~implementation of
this interface and contribute it. For the~comfort of the~contribution, default
abstract implementation of this interface is prepared for Modules contribution.
This \texttt{AbstractSimpleModuleGUIProvider} class provides automatic
validation based on the~requirements of the~underlying Module, handles adding
and removing of the~Module from the~Session and disables its configuration. It
can be used for the~most of the~basic cases. If there is more complex case, it
can provide the~implementation of the~interface from the~scratch.

Some of the~system objects support advanced GUI features. Rather than hard
coding these features I~decided to provide additional interfaces that are used
for access to the~specific behavior. The~Session editor can then check if the
provider class also implements these additional interfaces and if so, it can
provide access to this functionality. The~current list of these interfaces
follows.

\begin{samepage}
\begin{itemize}
  \item \texttt{IOpenable} - allows the~provider to open underlying resource
  (used for Programs)
  \item \texttt{IRunListener} - allows parts of the~Session to be notified about
  the~Session being run (used for the~GUI actions of system objects)
  \item \texttt{ISystemObjectChangeNotifier} - allows the~provider to be
  registered as a~notifier to the~change listener (used for population of
  the~change of the~underlying resources of Programs and obstacles)
\end{itemize}
\end{samepage}

\subsubsection{System Object Class Component}

Lets get back to the~\texttt{createExpandingPart} method. As mentioned before,
it creates the~general layout of the~expanding part. It also adds the~``Plus''
element which allows user to add new elements to this expanding part. The~action tied to the~plus button is execution of the~list dialog which is filled
with available system objects of the~given type. As you can probably guess,
after the~selection of the~system object, action is delegated to the~proper
implementation of the~\texttt{ISystemObjectGUIProvider} which handles the
backend action. At the~end of the~whole adding process, new visual
representation of the~system object is added to the~expanding part by the~call
to the~\texttt{createSystemObjectComponent} method which will be discussed
later. One thing that take me some time to figure it out was how to refresh the
SWT container after adding new components without destroying and recreating
whole editor which wouldn't be too much user friendly. The~magic is to invoke
\texttt{void layout(boolean changed, boolean all)} method with both changed and
all set to true on the~\textbf{parent} of the~container which content has been
changed. In this case it is supposed to call the~\texttt{layout} method on the
whole \texttt{ExpandBar}.

The rest of the~\texttt{createExpandingPart} method is fairly simple. It takes
the ids of the~system objects that should be shown loads the~provider for each
of them and delegates their creation to the~\texttt{createSystemObjectComponent}
method.

\subsubsection{System Object Component}

The last part of the~SessionEditor I~will describe here is the~mentioned
\texttt{createSystem\-ObjectComponent} method. It is responsible for creation of
the visual representation of one system object. It expects to get information
about the~parent container, system object GUI provider, id of the~system object
and its index in the~Session.

It prepares the~general container and places into it holder for error image,
name label, settings icon, remove icon. After that the~big object image is
added. Content of the~name label, presence of the~settings icon and settings
handler together with remove handler are just delegated to the~GUI provider
rather than doing some logic on their own. 

Decision whether double click on the~big image will open the~underlying resource
or whether the~notifier should be registered are evaluated based on the~fact if
the provider class implements proper interfaces.

\subsubsection{Validation of the~Editor}

When the~error icon placeholder is created, its reference together with the
reference to the~gui provider and system objects are wrapped into the
\texttt{SystemObjectValidator} class and added to the~list of validators. When
there is any change to the~content of the~Session itself, all validations are
invoked on all registered wrappers. This concept ensures that the~Session is
always validated and cannot be executed when validation fails.


\subsection{Script Program Wizard}
Script Program wizard is one of the~wizards executed as a~reaction to the
invocation of the~adding to the~Session action mentioned in the~section
\ref{subsubsec:GUIAbstractionLayer}. I~want to mention it because it uses
advanced capabilities of the~JFace wizards concept.

At the~beginning I~will describe, general concept of the~JFace wizards. If one
wants to create new wizard, he has to create a~class that implements
\texttt{IWizard} interface. JFace provides rather useful abstract implementation
of this interface called \texttt{Wizard} which provides the~basic pages and
situations handling. So one might rather extend this abstract class than
implement the~interface from the~scratch.

Class that implements \texttt{IWizard} represents the~whole wizard. Now we have
to add some pages to it. Each wizard page must implement interface of
\texttt{IWizardPage}. Again there is a~convenient abstract implementation
available called \texttt{WizardPage}. There are also some full implementations
provided by Eclipse. These can be included in our wizards and examples are
\texttt{WizardNewFileCreationPage} or \texttt{WizardNewFolderMainPage}.

The implementation of the~wizard instantiates wizard pages and provides the
implementation of the~\texttt{performFinish} method which is invoked once the
wizard is finished. Wizard pages are usually shown in the~same order they have
been added to the~wizard. If we have some special needs for changing the~order
or skipping some pages, we can provide custom implementation of the
\texttt{getNextPage(IWizardPage page)} method. This method gets current page as
a parameter and should return next page or null if there are no more pages.

In the~case of the~\texttt{ScriptProgramWizard} the~first page offers selection
whether user wants to select existing Program file or he wants to create new
empty one. Based on this decision next page is either
\texttt{ExistingFileSelectionPage} or \texttt{WizardNewFileCreationPage}. The~implementation of the~\texttt{getNextPage} method can provide the~whole wizard
flow information or it can provide only the~part that doesn't follow the~default
flow and then fallback to the~super implementation.

One more part of the~\texttt{ScriptProgram\-Wizard} is worth mentioning and it
is the~\texttt{Existing\-File\-SelectionPage} implementation. Surprisingly
Eclipse RCP doesn't provide wizard page implementation that would select existing resource
out of the~workspace although similar page is available in the~Eclipse IDE. This
led me to the~examination of the~existing Eclipse IDE wizard and to the~creation
of my own page which is similar to the~examined one.

This page consist of a~path text box which is read only and is intended only for
validation of the~selected path and of one button that is used to invoke the
selection dialog. While the~whole wizard page is not provided,
\texttt{ElementTreeSelectionDialog} is a~nice implementation of the~dialog that
can browse workspace and provide selection. The~dialog provides filtering
capabilities to allow only valid selections. The~filter implementation can be
seen in the~Algorithm~\ref{fig:ElementTreeSelectionDialogFiltering}.

\begin{algorithm}
  \caption{Filtering of the~ElementTreeSelectionDialog content}
  \label{fig:ElementTreeSelectionDialogFiltering}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=Java]
dialog.addFilter(new ViewerFilter() {
	
	@Override
	public boolean select(Viewer viewer, Object parentElement, Object element) {
		if (!(element instanceof IFile)) return true;
		IFile f = (IFile) element;
		return f.getFullPath().getFileExtension().equals(extension);
	}
});
\end{lstlisting}       
\end{algorithm}


The resulting wizard page is abstract enough to be used in other places in the
application where the~existing file selection page with filtering to some file
extension is necessary.

\subsection{Running}
Running of the~Session is invoked in the~similar fashion like running of the
Program inside any IDE. Run action is available on the~toolbar when some Session
editor is selected. Invocation of the~run actions itself quite easy and has to
take care of three things. First is to check consistency of the~Session to make
sure that the~Session is saved and valid. Second is to prepare logging framework
and console appending capabilities. Third is to switch the~perspective to the
running perspective which is focused on showing results and Monitors of the
running Session rather than Session editor itself.

\subsubsection{Commands} 
Eclipse RCP provides the~commands framework which is
described in section~\ref{subsec:decisions}. Run action is implemented using
this framework. To be able to provide command we have to first implement a~command handler by subclassing the~\texttt{AbstractHandler} and then contribute
it to the~\texttt{org.eclipse.ui.handlers} extension point. When this is done,
this handler can be referenced by its id.

Now we have to register a~command with some name by contributing to the
\texttt{org.\-eclipse.\-ui.\-commands} extension point and referencing the
command handler id. These steps might seem to be to complex and surplus but it will
allow future extensions to provide different handlers for this command in the
future if necessary. You can notice that while the~run command handler is
located in the~\texttt{net.\-zarubsys.\-robotplayground.\-gui.\-running} plugin
and it is contributed there, actual command registration is done in the
\texttt{net.\-zarubsys.\-robotplayground.\-gui.\-session} plugin. Reason to this
layout is that running plugin is considered to be only a~tool to the~Session and it is
a decision of the~Session plugin to take advantage of this implementation of the
run handler.

So we do have the~command but there is no place where it is displayed. To make
the~command to show somewhere we are able to provide extension to the
\texttt{org.eclipse.ui.menus} extension point. The~extension provides reference
to the~command by id, its icon, label and style. But we want it to be shown only
when the~Session editor is active. This can be achieved by the~concept of
\texttt{visibleWhen} conditions. See the~Algorithm~\ref{fig:contributionOfRun}
for the~example.

\begin{algorithm}
  \caption{Contribution of the~Run action to the~toolbar}
  \label{fig:contributionOfRun}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=XML]
<extension
         point="org.eclipse.ui.menus">
      <menuContribution
            allPopups="false"
            locationURI="toolbar:org.eclipse.ui.main.toolbar">
         <toolbar
               id="net.zarubsys.robotplayground.gui.session.toolbar">
            <command
                  commandId="net.zarubsys.robotplayground.gui.session.run"
                  icon="icons/run.png"
                  label="Run"
                  style="push">
               <visibleWhen
                     checkEnabled="false">
                  <with
                        variable="activeEditorId">
                     <equals
                           value="net.zarubsys.robotplayground.gui.session.editor">
                     </equals>
                  </with>
               </visibleWhen>
            </command>
         </toolbar>
      </menuContribution>
   </extension>
\end{lstlisting}       
\end{algorithm}

Now we have the~icon visible when needed and its activation invokes
\texttt{RunCommandHandler} class. When this handler is invoked it checks
validity of the~Session, prepares console logging facility and switches to the~run
perspective. We will discuss the~latter two in the~further.

\subsubsection{Console Logging}
Programs and API calls of the~Session can produce logging output. We want users
to have access to this log output to be able to debug and improve their Programs
or fix errors.

I have decided that the~proper solutions is to reuse the~existing Console
facility of the~Eclipse IDE. It provides content searching and many of Eclipse
users are familiar with its look and usage.

To achieve this goal two subtasks must be handled. First use the~internal
Eclipse console. Second add custom appender to the~Log4j to be able to redirect the
logged messages to the~console output stream.

\paragraph{Eclipse Console} is a~facility that encapsulates the~console usage.
New console can be added by instantiating the~\texttt{MessageConsole} class with
a name and image descriptor and by adding it to the~console manager. We can get
the console output stream from the~message console instance and set it to be
activated on write which will activate the~console view every time something is
logged into the~console. See the~Algorithm
\ref{fig:initializationOfMessageConsole} for details. We will use the~output stream to pass it to the~Log4j appender as will be describe in the~next paragraph. It is not necessary to take
care about console closing. Once we close the~output stream message console will
be deactivated but it will stay in the~console view until the~user removes it by
the UI action.

\begin{algorithm}
  \caption{Initialization of Own Message Console}
  \label{fig:initializationOfMessageConsole}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=Java]
MessageConsole console = new MessageConsole("Session '" + session.getName() + "'", null);
ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] {console});
		
IOConsoleOutputStream os = console.newOutputStream();
os.setActivateOnWrite(true);
\end{lstlisting}       
\end{algorithm}

\paragraph{Log4j Appender} is an~interface to be implemented to be able to
provide own appender to the~Log4j configuration. There is a~skeleton
\texttt{AppenderSkeleton} class which provides the~common functionality. My
\texttt{ConsoleLogAppender} is designed as a~kind of the~singleton class but
concept of Appenders instantiation prevented me from applying of the
usual singleton concept. It is enforced to have only one instance of this
appender though and this instance can be accessed. It is singleton to be able to
add and remove output streams into which the~logged message should be copied
even after the~instance has been created.

The output stream received from the~Message console as seen in Algorithm
\ref{fig:initializationOfMessageConsole} is then passed to the~Appender.
Implementation of \texttt{IProgramFinishedListener} is added to the~Session to
be able to remove the~output stream from the~Appender once the~execution of the
Session is finished.

\subsubsection{Perspective}
\label{subsub:perspectiveRun}
To provide better layout of views and editors for Session execution I~decided to
implement new perspective with slightly different layout than default
perspective. Implementation of the~additional perspective is very similar to the
implementation of the~default perspective as described in the~section
\ref{subsec:IperspectiveFactory}. 

The difference is in the~way how we tell the
Eclipse to make this perspective available. Same as the~default perspective the
additional one has to be contributed to the~extension point
\texttt{org.eclipse.ui.perspectives}. Eclipse RCP has perspective switching
facility built-in. But what we really want is to provide easy switching shortcut
to the~UI. This can be done by contributing to the
\texttt{org.eclipse.ui.perspectiveExtensions} and adding the
\texttt{perspectiveShortcut} elements referring to the~ids of perspectives to be
shown in the~switching panel.

\subsubsection{Stopping}
Stopping the~running Session is very similar to the~starting one. For this
purpose \texttt{Stop\-Command\-Handler} is implemented. It fires the~stop signal
on the~Environment of the~running Session. It is contributed to the~toolbar of the
console view. Its location URI is
\texttt{toolbar:\-org.eclipse.\-ui.console.\-ConsoleView}.

\chapter{Joystick Input}
\label{chap:joystickInput}
One of the~bundles of functionality provided outside of the~core implementation
will be the~basic joystick handling. It will be able to access a~joystick, load
its signature, read state of its buttons and read positions of X and Y axis.

Device object will be created to encapsulate access to the~joystick and Module
object will be created to provide higher level access to the~joystick state from
the programs through the~API.

Access to the~joystick will be done through the~JNI\footnote{Java Native
Interface} calls. Native libraries for Linux and possibly for the~MS Windows
platforms will be provided as a~part of the~bundle.

\section{Joystick API}
In Linux, joystick is accessed using through the~file descriptor. Access to the
events from the~joystick is done through non-blocking reading from the~file
descriptor. Structure \texttt{js\_event} is received. It provide type
information which distinguishes if the~button state was changed or position of the~axis was
changed. Then information about the~id of the~changed element together with the
current value is provided.

To provide the~access to the~joystick I~have created
wrapper of the~native access called \texttt{JoystickNativeAccessor} and the~helper class. 
The wrapper can through the~JNI open the~file and get the~file descriptor. Using
this file descriptor, device signature can be read or the~file can be closed.

Reading of the~joystick events is done by starting the~JNI endless loop, which
reads events and passes them back to Java to the~provided callback. During each
iteration, \texttt{doClose} method is invoked on the~callback to check if the
loop should be terminated. Implementation of the~callback is the~native accessor
itself. Convenience of this layout lays in the~fact that the~callback can easily
change state of the~accessor which holds the~representation of the~joystick
state. While there is no intention to reuse this callback, it is safe to say
that from the~objective point of view, this layout is ok.

In Java there is a~helper class used to gain access to the~native accessor.
This helper holds the~register of opened native accessors and is implemented as a~singleton.
Instantiation of the~native accessor starts a~new thread which opens the~device
and starts the~reading loop. When the~closing method is called on the~helper,
native accessor is removed from the~register and underlying file is closed. This
causes the~reading loop to be terminated.

Native libraries are compiled as standalone projects and included into the
Eclipse Plugins. For Eclipse Bundle ClassLoader it is necessary to have the
information about the~native library registered in the~MANIFEST.MF file. Part of
the registration can be a~platform filter. This way several libraries can be
registered in the~same bundle but only the~one which complies with the~platform
filter is accessible during the~runtime of the~product.

More information about the~native joystick libraries is located in the~Appendix
\ref{A:chap:JNI}.

\section{Joystick Device}
Previous section described how I~implemented access to the~native device.
Joystick Device is the~first level of abstraction of this accessor. It
encapsulates the~native accessor to the~\texttt{IDevice} envelope to make it a~system object.

It is parametrized with the~\texttt{JoystickDeviceConfiguration} config. This
config provides the~information about the~device path. It is very abstract to
comply with all platforms.

Constructor of the~Joystick Device gains the~native accessor through the
described accessor helper singleton. This as mentioned causes opening of the
device and start of the~reading loop. While the~native accessor holds the~state
of the~joystick, methods accessing the~state of buttons and axis can be just
delegated to the~native accessor. The~information will be fresh because the
state of the~native accessor is periodically updated by the~reading thread.

\section{Joystick Module}
Joystick Module is only a~thin envelope over the~joystick device. This is caused
by the~rather direct mapping of the~methods to the~native accessor without any
need of data transformation or so. This situation could be different if a~device
with direct coordinates would be used. Then some recalculation of values would
be necessary in order to provide the~requested information.

\chapter{Dummy Device}
\label{chap:dummyDevice}
The name Dummy Device might sound strange but it actually is exactly what the
name states, device which is used for testing. Testing of the~application,
testing of the~script Programming skills, testing of AI, testing of concepts.
Whichever we choose, it is important to understand that this virtual device is
not just something created for fun. It is usable in the~real life although it is
virtual.

Now you know how important it is, let's talk what it actually is. Dummy Device
is a~virtual object which knows its coordinates and its direction. Both can be
altered using API call of the~respective Module. It also comes with the~Module
of obstacles. This Module loads obstacle file and is able to give information
about possibility to go to some certain coordinates. There is also one Monitor
available. It is a~Map Monitor. It combines data from the~Device Module and
obstacles Module. When the~Device crashes into some obstacle or leaves the
designated map area, this Monitor raises a~stop signal. Its main purpose is to
provide visual representation of what's happening with the~Device.

\section{Backend Implementation}
At this point you probably understand, that implementation of such Device and
surrounding elements is not a~hardcore programming. Its implementation might be
taken as a~complete example of how to implement Device together with its
wrapping Module and of how to implement Module, which is standalone and doesn't
require any Device.
And last but not least of how to implement Monitor together with visual
representation.

\subsection{Dummy Device}
Dummy Device is a~simple container that holds the~x and y coordinates together
with the~direction. Coordinates are held as integers. The~direction is also
held as an~integer. The~representation of its value is a~responsibility of the
Module rather than the~of the~Device. 

While there can be multiple Programs running in parallel, it is necessary to
ensure that any changes of the~state are atomic. To achieve this I~introduced
the \texttt{ReentrantLock} to the~implementation. Every operation checks, that current thread holds this lock before changing the~data. This way it is ensured that only the~thread that
holds the~lock can change the~data. Every other thread that want to access the
data modifying methods is held at the~point of acquiring of the~lock. It is not
necessary to synchronize any actions inside the~changing methods, because inside
the thread which holds the~lock, operations run in sequence and other threads
are held at the~lock acquisition.

Dummy Device is configured by the~\texttt{DummyDeviceConfiguration} which
provides the~initial coordinates and initial direction.

\subsection{Dummy Motion Module}
Dummy Motion Module is wrapping layer of abstraction above the~Dummy Device. It
provides manipulation operations to the~API and encapsulates the~logic of Dummy
Device movements.

This Module takes care about the~lock acquisition as described in the~previous
section. In this moment, every call to the~\texttt{move} or \texttt{rotate}
methods, acquire the~lock, does the~operation and releases the~lock. Scenario
where the~Program acquires the~lock and then does a~sequence of operations is
not currently supported because long running operations could corrupt the~pseudo
runtime behavior of the~system.

Rotate operation simply adds the~incoming value to the~current value of
the Device direction. Value is now interpreted as degrees and going over 360 has
been taken care of. It is an~open question whether the~direction should be held
in the~orthogonal fashion or degrees. Move operation takes care about the
approximation of the~resulting coordinates of the~move using rounding. See the
algorithm~\ref{fig:dummyDeviceMove} for an~example.

Event is dispatched after each move or rotate operation so the~listening Modules
or Monitors can react to this event.

\begin{algorithm}
  \caption{Implementation of the~Move Operation in the~Dummy Motion Module}
  \label{fig:dummyDeviceMove}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=Java]
@Function(description = "Moves the~dummy device by the~given distance in the~current direction. It is possible to go backward using values < 0")
public void move(@Param(name = "distance") Integer distance) {
	double radians = Math.toRadians(device.getDirection());
	int dx = (int) Math.round(Math.sin(radians) * distance);
	int dy = (int) Math.round(Math.cos(radians) * distance);
	device.lockMovementsAccess();
	try {
		device.setX(device.getX() + dx);
		device.setY(device.getY() + dy);
	} finally {
		device.unlockMovementsAccess();
	}
	env.dispatchNotification(this, DummyMotionNotificationCause.MOVE);
}
\end{lstlisting}       
\end{algorithm}

\subsection{Dummy Obstacles}
Purpose of the~Dummy Obstacles Module was mentioned at the~beginning of this
Chapter. It takes the~endless world of the~plain empty desk to another level by
adding obstacles and by adding boundaries to the~world map.

This Module is configured by \texttt{DummyObstaclesModuleConfiguration} class.
It holds the~path to the~file containing map definition. It also provides static
method that can load this map definition file to the~\texttt{MapContainer}. This
container is a~holder of the~list of \texttt{BitSet} instances each representing
one line of the~map file. Obstacles are defined in the~map file by character
\texttt{'x'} and empty places by \texttt{'o'}.

Dummy obstacles Module provides only one method to the
API - \texttt{isObstacleAhead}.
This method validates the~current position to ensure it is on the~map. It
can return information whether move to the~distance of 1 to the~given direction
from the~given position would result into the~crash to the~obstacle. The~calculation is done in the~very similar fashion to the~Dummy Motion Module and
it would definitely be a~candidate to refactoring.

This Module also provides two other methods \texttt{isOnTheEdge} and
\texttt{isOnTheObstacle}. These are not registered into the~API because these
are not intended to be used from Programs. They are to be used by Dummy Monitor.

\subsection{Dummy Monitor - Map}
As stated before, Dummy Monitor verifies current position of the~Device after
each change using the~notifications facility. If it finds out that the~Device is
out of the~map or is on the~obstacle, it stops the~execution of the~Session and
logs this error.

It also does the~real monitoring meaning that each change of the~position of the
Device is written into the~log to be able to track the~motion and evaluate the
algorithms. Besides this feature, it also allows listeners to register and after
each valid event received by the~Monitor, it prepares the~information holder
containing all the~useful data about the~change and passes this to all
registered listeners. This concept is used for the~connection between the~GUI map with this
backend Monitor.

\section{GUI Implementation}
Dummy Device bundle contains Monitor. This Monitor is responsible for handling
validity of the~position of the~Device. But that is not all. Its main purpose is
to visualize the~position of the~Device and obstacles on the~map. This map was
realized as an~Eclipse view which is plugged into the~Run perspective.

As described before, core framework supports concept of notifications or
messages. Movement or rotation of the~Dummy Device is the~cause for the
notification. By putting these two together, we can get an~event based concept
of the~visualisation. This is actually useful since we don't need to create any
separate threads for loops.

At the~very beginning of the~development, we tried to create the~visualization
through the~generic SWT components. The~success was only partial as the~solution
suffered from the~serious performance issues. Due to this observation, we
decided to move the~visualization to the~Java2D framework.

Java2D is a~framework that comes with Java Standard Edition and there are no
external libraries needed. Official Oracle website states that ``Java2D
API provides two-dimensional graphics, text, and imaging capabilities for Java
programs through extensions to the~Abstract Windowing Toolkit''. It can take
advantage of system graphic acceleration and its performance boosted over the
years.

While the~whole application is created using SWT libraries, first step was to
embed the~AWT\footnote{Abstract Widget Toolkit} into the~SWT layout. Fortunately SWT
provides this support through the~\texttt{SWT\_AWT} class that can create new
frame inside of a~SWT \texttt{Composite} as long as this carries the
\texttt{SWT.EMBEDDED} flag. At this point I~would like to note that these days
\texttt{JPanel} is used. It is a~newer API replacement of AWT components but the
principal stays the~same.

Second struggle was to allow scrolling of this AWT panel. We have achieved this
capability by wrapping of the~panel into and instance of
\texttt{ScrolledComposite} class. Using this approach, panel can be resized long
after its initialization, when the~Monitor is actually passed to the~view.

Third thing was to use the~\texttt{JPanel} correctly to display the~grid,
obstacles and object - car properly. Our implementation of \texttt{JPanel} takes
care about drawing in \texttt{void paint\-(Graphics g)} method. The~\texttt{Graphics} argument is used to access Java2D capabilities. Since
many versions of Java ago, it can be casted to \texttt{Graphics2D} to
unlock many extended features.

Lines forming the~grid are drawn using the~simple \texttt{drawLine} method using
the size of the~map and constants. Images of car and obstacle are loaded into the~
form of \texttt{BufferedImage} using \texttt{ImageIO} tool. Obstacles are then 
just drawn onto the~proper position. Drawing of the~car is little bit more complex,
because the~car can rotate freely. To be able to provide this capability we had
to use \texttt{AffineTransform}. This transform is instantiated and then
provided with variety of transformation properties from which I~use rotation and
translation. Once it's properly configured, it is passed to the
\texttt{drawImage} on the~graphics. This way, transformations are quick and
efficient.

Using this approach, animations are smooth and CPU load is practically
non-existing. What's more this concept can be easily extended to the~form that
can be much more attractive for users and can bring more information such as
visited places, target visualization and others. Unfortunately this is beyond
the scope of this project.

\chapter{Testing}
\label{chap:testing}
Testing of the~application was done on several layers. I~will now describe
three of them.

\section{Unit Tests}
Unit testing is important part of the~application development. Unfortunately I~haven't created the~unit tests from the~beginning of the~project. Thus the~code
is not covered by tests completely.

Unit testing in the~Eclipse application has its specifics because it uses
alternative class loaders which understand bundles, fragments, plugins, and
other Eclipse specific elements.
Normally if you want to test some class you usually locate tests into the~same
package to be able to access package private fields and methods and not to make
them public. This approach has one big problem. If you distribute your
application, you cannot easily omit the~tests in the~production packages. On the
other hand in the~Eclipse based application what you can do is to create a~test
fragment. As mentioned in the~section~\ref{subsec:eclipseFragment} fragment
expands the~classpath of its host plugin. This expansion is, thanks to Eclipse
class loaders, transparent and thus if you locate your test code into the
package of the~same name in the~fragment, it is from the~point of class loading
the same thing as if you would locate it next to the~class you are about to
test. These fragments might be used in the~development only and skipped easily when building the~final product.

To demonstrate this approach I~have created the~test fragment called
\texttt{net.\-zarubsys.\-robotplayground.\-dummyDevice.\-test}. This fragment
contains one test case which tests the~\texttt{DummyDevice} class. As I~said I~haven't
covered most of the~code by tests but I~think that unit testing is very
important step in the~process of software development so I~at least described
how it can be done in the~environment of an~Eclipse application.


\section{Usability Tests}
At the~end of the~product development I~have arranged some testing Session that
can be called usability testing. I~have separately invited two persons to try to
test the~product. Help was not finished by that time and it was replaced by a~brief explanation of the~application procedures. Both of these subjects have
some experience with the~problem domain - commanding of external devices, as
well as with the~software development. Based on this coverage of knowledge I~would say
that the~testing method is somewhere between Hallway testing and Expert review.
Because of this and the~amount of resources available I~assumed that two
subjects would be enough for discovering of the~vital flaws in the~application
or UI design.

Output of this testing was a~list of minor bugs and suggestions to elements
renaming. These were than incorporated into the~application design. The~most important result of the~usability testing was the~suggestion to introduce the~Run perspective as
described in section~\ref{subsub:perspectiveRun}. Both of the~participants
pointed to the~fact that the~distinction between setup of the~Session and
related components and actual execution of the~Session is hard and confusing. As
a result run perspective was created. Application automatically switches into
this new perspective when user executes a~Session. Both participants agreed that
this improvement effectively cleared the~confusion.

Besides the~facts described in the~previous paragraph, any other flaws were not
discovered.


\section{Beta Testing}
This project can be described as a~small project. Not by the~amount of code or
time spent on it but by the~count of developers. I~have been the~only one
working on the~project so far. This fact leads to the~selected techniques of the
product testing. There is no testing division which would test the~project
through every minor version to the~end of the~development. Beta testing is the
procedure during which designated users perform standard as well as non-standard
operation and procedures in the~piece of software. It is aimed to find flaws in
the GUI usability, bugs in the~UI behavior and bugs in the~semantics of the
application.

For the~beta testing I~have prepared a~task to be accomplished using the~Dummy
Device and surrounding elements together with the~default Script programming
language. The~task was to implement navigation from the~initial point to the
target without hitting any obstacle or leaving the~map. This task was to be
implemented using either BFS or DFS, possibly also using A* with some heuristic
function.

This task was completed by me and by one independent tester. Before we even
started we both found that we miss few important list manipulating functions.
These were \texttt{push}, \texttt{contains} and \texttt{pull}. After finishing
the implementation of these functions we were able to proceed and finish the
task.

We both agreed on the~following possible improvement. Script Program would
benefit from the~syntax highlighting editor which would check brackets
consistency. Minor bugs were found during the~testing. Most of them were just
minor adjustments like correction of labels, layouts and similar tasks. I~fixed
most of them right away.

Although the~scripting language now contains lot of functions which cover most
of the~needs of the~user, specific needs may arise and new functions or
improvements to existing functions will be required. This is not a~particular
problem, because it is fairly easy to add new functions to the~scripting
language. The~other way how to deal with this need is to plug in other
languages. These might be Lisp, Prolog, Perl, Python or others. This is
discussed in section~\ref{sec:futureExtensions}.
  
  
The conclusion from the~testing is following. The~application is fully
suitable for the~purpose of AI development and testing for example in the~school
projects. This of course doesn't cover whole wide area of possible usages of
this software. Anyway I~think that it is a~good result which proves the~analysis
and iterative approach taken on this project to be correct and satisfactory.
Sample of the~BFS implementation can be found in the~default workspace which is
bundled with the~application package on the~enclosed CD.


\chapter{Conclusion}
\label{chap:conclusion}
\section{Project Definition}
Definition of this project states that the~result of my work should be a~program
bundle usable for complex control and programming of external devices (robots) or their
simulation. The~main requirement to the~project was its modularity. It was a~goal to allow easy implementation of additional support for new devices,
programming languages and other functionality. It was required that resulting
bundle should be usable on MS Windows as well as on Linux operating systems
including possible native libraries.
Last functional requirement was to create at least one implementation of the~Device
or simulation to demonstrate possibilities of the~resulting product. It was also
required to provide user's guide and developer's guide to the~points of extensions.

\section{Result Evaluation}
As you can read in this thesis, I~fulfilled all the~goals described in the
project definition. Possibility to control and program external devices or
simulations is declared in the~general description of the~concept in section
\ref{sec:requiredFeatures} and later in the~description of the~Dummy Device -
showcase implementation of the~new Device and surrounding tools in the
Chapter~\ref{chap:dummyDevice}.

Modularity of the~project is stated from the~very beginning in the~goals
description in section~\ref{subsec:descriptionOfStructure}. It was accounted
into the~selection of the~framework in Chapter~\ref{chap:frameworks} and
modularity aids of the~selected Eclipse framework were described in detail in
section~\ref{sec:EclipsePlatformAndRCP}. In the~section
\ref{sec:frameworkCapabilites} I~have described how can this project benefit
from the~modularity concepts provided by the~framework. The~Chapter~\ref{chap:implementationOfTheCore} describing the~implementation of the~core of the~project shows how the~new capabilities and features can be added to the
application and Chapter~\ref{chap:dummyDevice} shows how these Modules might be
implemented.

General possibility to run the~resulting bundle on both MS Windows and Linux
platforms was ensured by the~selection of the~programming language as described
in Chapter~\ref{chap:choosingProgrammingLanguage}. Same was taken into account
in the~selection of the~framework. Chapter~\ref{chap:joystickInput} shows how I~took care of portability when native code came into the~game. The~requirement
to create at least one implementation showing possibilities of the~framework was fulfilled as described in Chapter~\ref{chap:dummyDevice}.

Complete user's guide is available inside the~application as well as in the
appendix~\ref{A:chap:usersGuide} as a~part of this thesis. Developer's guide is
also available as a~part of the~application help and can be found in the
appendix~\ref{A:chap:developersGuide}. All the~source code, final
application and this thesis can be found on the~enclosed CD. Its content is described in appendix~\ref{A:chap:CDContent}.

During writing of this thesis and during the~implementation of the~project
itself I~have fulfilled all the~goals

\section{Contribution}
This project contributes in more than one way. It provides an~example of fully
functional Eclipse RCP based application and shows how this platform can be
utilized to create complex application with fully native look and feel with good
performance, easy deployment and extraordinary portability.

My description of concepts and techniques related to the~Eclipse Platform starts
on the~high level of abstraction and goes into important details which must be
taken into consideration when working with the~Eclipse platform. This can be
taken as a~set of guidelines and together with the~example in the~form of source
code and points to the~literature it forms a~good manual for beginners.

Previous two paragraphs were about benefits for those who want to implement some
project using Eclipse platform. This project is called Robot Playground and it
definitely brings benefits to the~people involved in this area. As discussed in
Chapter~\ref{chap:currentSolutions}, there is not many projects of this kind
available and this one has a~benefit of great modularity and it is open source
project so the~community is able to extend it and modify it to the~exact shape
good for their usage. It can be used by variety of users from hobbyists, as a~platform for school assignments for AI algorithms to use in the~real world
projects as a~base for the~control applications.

\section{Future Extensions}
\label{sec:futureExtensions}
Although this project exceeded its definition, I~can still see many points where
it can be extended.

\subsection{Scripting Program Improvements}
The scripting language described in section~\ref{sec:scriptProgram} is based on
the old parsing core and is very verbose. Despite this fact it was proven as
very successful and usable over the~time. I~would like to reimplement it using
the Xtext project. Xtext project is a~framework for development of programming
languages and domain specific languages. It covers all aspects of a~complete
language infrastructure, from parsers, over linker, compiler or interpreter to
fully-blown top-notch Eclipse IDE integration~\cite{xtext}. This would provide
fully featured IDE for writing of the~scripts including syntax highlighting and it
would be easier to get rid of some verbose idioms mostly around the~variables
handling.

\subsection{Implementation of Additional Programming Languages}
While scripting language is powerful, easy and general enough to be used as a~basic programming language for this project, there are some languages that are
long proven as good for AI programming although in these days they are becoming
a little bit less popular for various reasons. I~am now talking about Lisp and
Prolog. I~would like to hook up the~Lisp and Prolog interpreters to the~project.
One step toward this layout was taken in the~\ref{subsec:EnvironmentAndAPI}
where the~API was done abstractly enough to allow easy calls from any
programming language using only very thin translation layer.

There is a~pure Java implementation of Common Lisp called Armed Bear Common
Lisp. This implementation runs inside the~JVM. This project looks promising for
this usage and is licensed under the~GPL with the~Classpath exception so it can
be used inside this project without the~need to licence this project under the
GPL. Website of the~project is \url{http://common-lisp.net/project/armedbear/}.

There is also an~implementation of Prolog as a~Java library. It is called GNU
Prolog for Java and allows one to execute goals from within the~Java
application. Its website is \url{http://www.gnu.org/software/gnuprologjava/}.

\subsection{Moving to the~Eclipse 4.2.x Platform}
Although Eclipse Platform 3.7.x runs just fine, it would be good to move this
project to the~new platform. In the~4.2 version construction of the~application
torso runs in the~totally different fashion. Every configuration of the
application is an~ECore model and it sounds promising. This project moved from
3.7 to 4.2 could be a~good example of migration guide in practice.


\chapter{Used Shortcuts}
\begin{itemize}
  \item AI - Artificial Intelligence
  \item API - Application Programming Interface
  \item GC - Garbage Collector
  \item GNU - GNU's Not Unix! (recursive acronym)
  \item GUI - Graphical User Interface
  \item IDE - Integrated Development Environment
  \item IO - Input/Output
  \item JDK - Java Development Kit
  \item JFC - Java Foundation Classes
  \item JNI - Java Native Interface
  \item JRE - Java Runtime Environment
  \item HW - Hardware
  \item LGPL - GNU Lesser General Public License
  \item OS - Operating System
  \item OSGi - Open Services Gateway initiative
  \item PC - Personal Computer
  \item RCP - Rich Client Platform
  \item RFRS - Ready for Rational Software
  \item SWT - Standard Widget Toolkit
  \item UI - User Interface
  \item URI - Uniform Resource Identifier
  \item VM - Virtual Machine
\end{itemize}